﻿using _2DLineCamera.HikCamera;
using _2DLineCamera.IKCamera;
using _2DLineCamera.Models;
using HalconDotNet;
using HslCommunication;
using HslCommunication.Algorithms.Alarm;
using HslCommunication.Profinet.Melsec;
using IKapBoardClassLibrary;
using IKapC.NET;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;



namespace _2DLineCamera
{
    public partial class Form1 : Form
    {
        public AutoZone autoZone = new AutoZone();
        public LineTriggerCamera camera = new LineTriggerCamera();
        public int ret = 0;
        BufferToImage buffertoimg = null;
        Config configfil = new Config();
        public HikVisionCamera HikLeftCamera = new HikVisionCamera();
        public HikVisionCamera HikRightCamera = new HikVisionCamera();
        public bool continuousImage = false;
        public Task GetImage_task_Hik;

        public bool PLC_Connection = false;
        public bool isLeftPinStatus = false;
        public bool isRightPinStatus = false;
        public int ImageNumber = 0;

        Tool tool = new Tool();
        public bool SaveImagecheck = false;
        public int SaveImageCount = 0;
        public int Collection_method = 0;
        bool Configurationfile = true;
        public MelsecMcNet PLC = new MelsecMcNet();
        public OperateResult operateResult = new OperateResult();
        public int IkCameraNum = 0;
        public HObject manualImage = new HObject();
        public HObject CalibrationImage = new HObject();

        public HTuple manualImage_width = new HTuple();
        public HTuple manualImage_Height = new HTuple();

        public HTuple CalibrationImage_width = new HTuple();
        public HTuple CalibrationImage_Height = new HTuple();
        public int CalibrationLInenumber1 = 0;
        public int CalibrationLInenumber2 = 0;
        public string MesJudgeL = "PASS";
        public string MesJudgeR = "PASS";
        public bool CompensationValueL = false;
        public bool CompensationValueR = false;
        public string SaveImageTestReult = "OK";
        public string SaveImageTestReultPIN = "OK";
        public string CsvTestReult = "OK";

        public HDrawingObject DraROI;
        public HDrawingObject DraROICalibration;

        public int Now_Product_ID = 0;
        ProductList productList = new ProductList();

        public int EndLeftIKCamera = 0;
        public int EndRightIKCamera = 0;
        public int StartMinLeftHikCamera = 0;
        public int StartMinRightHikCamera = 0;
        public int EndMinLeftHikCamera = 0;
        public int EndMinRightHikCamera = 0;

        public HTuple Calibration_CameraLeft = new HTuple();
        public HTuple Calibration_CameraRight = new HTuple();
        public HTuple HikRightPose = new HTuple();
        public HTuple HikRightCameraParam = new HTuple();
        public HTuple HikLeftPose = new HTuple();
        public HTuple HikLeftCameraParam = new HTuple();

        public ProductManager ProductTotal = new ProductManager(Directory.GetCurrentDirectory() + @"\ProductTotal.ini");

        public string LeftStationCode = "";
        public string RightStationCode = "";

        public bool Measure_record = false;

        public HObject testRegion = new HObject();

        public List<Measure_Result> LeftStationMeasureResult = new List<Measure_Result>();
        public List<Measure_Result> RightStationMeasureResult = new List<Measure_Result>();
        public PinCheck LeftPinStationMeasureResult = new PinCheck();
        public PinCheck RightPinStationMeasureResult = new PinCheck();

        public int Region1nenumber = 0;
        public int Region2nenumber = 0;
        public int Region3nenumber = 0;

        //创建模型区域和掩膜区域
        public HObject ModelRegion = new HObject();
        public HObject ModelDeletRegion = new HObject();
        public Form1()
        {
            InitializeComponent();
            hSmartWindowControl5.MouseWheel += HSmartWindowControl5_MouseWheel;
            hSmartWindowControl1.MouseWheel += HSmartWindowControl1_MouseWheel;
            hSmartWindowControl2.MouseWheel += HSmartWindowControl2_MouseWheel;
            hSmartWindowControl3.MouseWheel += HSmartWindowControl3_MouseWheel;
            hSmartWindowControl4.MouseWheel += HSmartWindowControl4_MouseWheel;
            hSmartWindowControl6.MouseWheel += HSmartWindowControl6_MouseWheel;
            autoZone.TheHeight = this.Height;
            autoZone.TheWidth = this.Width;
            autoZone.setTag(this);



            DataGridViewColumn[] leftDataGridViewColumns = new DataGridViewColumn[]
            {
                new DataGridViewTextBoxColumn()
               {
                   HeaderText="序号"
               },
               new DataGridViewTextBoxColumn()
               {
                   HeaderText="测量名称"
               },
               new DataGridViewTextBoxColumn()
               {
                   HeaderText="测量值"
               },
               new DataGridViewTextBoxColumn()
               {
                   HeaderText="设定值"
               },
               new DataGridViewTextBoxColumn()
               {
                   HeaderText="值下限"
               },
               new DataGridViewTextBoxColumn()
               {
                   HeaderText="值上限"
               }
            };
            DataGridViewColumn[] righttDataGridViewColumns = new DataGridViewColumn[]
            {
                new DataGridViewTextBoxColumn()
               {
                   HeaderText="序号"
               },
               new DataGridViewTextBoxColumn()
               {
                   HeaderText="测量名称"
               },
               new DataGridViewTextBoxColumn()
               {
                   HeaderText="测量值"
               },
               new DataGridViewTextBoxColumn()
               {
                   HeaderText="设定值"
               },
               new DataGridViewTextBoxColumn()
               {
                   HeaderText="值下限"
               },
               new DataGridViewTextBoxColumn()
               {
                   HeaderText="值上限"
               }
            };

            DataGridViewColumn[] leftPinDataGridViewColumns = new DataGridViewColumn[]
            {
                new DataGridViewTextBoxColumn()
               {
                   HeaderText="序号"
               },
               new DataGridViewTextBoxColumn()
               {
                   HeaderText="测量名称"
               },
               new DataGridViewTextBoxColumn()
               {
                   HeaderText="长"
               },
                new DataGridViewTextBoxColumn()
               {
                   HeaderText="宽"
               },
                 new DataGridViewTextBoxColumn()
               {
                   HeaderText="水平X"
               },
               new DataGridViewTextBoxColumn()
               {
                   HeaderText="水平Y"
               }, 
            };
            DataGridViewColumn[] rightPinDataGridViewColumns = new DataGridViewColumn[]
            {
                new DataGridViewTextBoxColumn()
               {
                   HeaderText="序号"
               },
               new DataGridViewTextBoxColumn()
               {
                   HeaderText="测量名称"
               },
               new DataGridViewTextBoxColumn()
               {
                   HeaderText="长"
               },
                new DataGridViewTextBoxColumn()
               {
                   HeaderText="宽"
               },
                 new DataGridViewTextBoxColumn()
               {
                   HeaderText="水平X"
               },
               new DataGridViewTextBoxColumn()
               {
                   HeaderText="水平Y"
               },
            };

            dataGridView1.Columns.AddRange(leftDataGridViewColumns);
            dataGridView2.Columns.AddRange(righttDataGridViewColumns);

            dataGridView3.Columns.AddRange(leftPinDataGridViewColumns);
            dataGridView4.Columns.AddRange(rightPinDataGridViewColumns);

            dataGridView1.RowHeadersVisible = false;
            dataGridView2.RowHeadersVisible = false;

            dataGridView3.RowHeadersVisible = false;
            dataGridView4.RowHeadersVisible = false;

            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
            dataGridView2.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;

            dataGridView3.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
            dataGridView4.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
        }

        private void HSmartWindowControl6_MouseWheel(object sender, MouseEventArgs e)
        {
            //HSmartWindowControl控件的区域
            Rectangle rect = hSmartWindowControl6.RectangleToScreen(hSmartWindowControl6.ClientRectangle);
            //滚动时，鼠标悬停在在HSmartWindowControl控件上
            if (rect.Contains(System.Windows.Forms.Cursor.Position))
            {
                //缩放
                hSmartWindowControl6.HSmartWindowControl_MouseWheel(sender, e);
            }
        }

        private void HSmartWindowControl4_MouseWheel(object sender, MouseEventArgs e)
        {
            //HSmartWindowControl控件的区域
            Rectangle rect = hSmartWindowControl4.RectangleToScreen(hSmartWindowControl4.ClientRectangle);
            //滚动时，鼠标悬停在在HSmartWindowControl控件上
            if (rect.Contains(System.Windows.Forms.Cursor.Position))
            {
                //缩放
                hSmartWindowControl4.HSmartWindowControl_MouseWheel(sender, e);
            }
        }

        private void HSmartWindowControl3_MouseWheel(object sender, MouseEventArgs e)
        {
            //HSmartWindowControl控件的区域
            Rectangle rect = hSmartWindowControl3.RectangleToScreen(hSmartWindowControl3.ClientRectangle);
            //滚动时，鼠标悬停在在HSmartWindowControl控件上
            if (rect.Contains(System.Windows.Forms.Cursor.Position))
            {
                //缩放
                hSmartWindowControl3.HSmartWindowControl_MouseWheel(sender, e);
            }
        }

        private void HSmartWindowControl2_MouseWheel(object sender, MouseEventArgs e)
        {
            //HSmartWindowControl控件的区域
            Rectangle rect = hSmartWindowControl2.RectangleToScreen(hSmartWindowControl2.ClientRectangle);
            //滚动时，鼠标悬停在在HSmartWindowControl控件上
            if (rect.Contains(System.Windows.Forms.Cursor.Position))
            {
                //缩放
                hSmartWindowControl2.HSmartWindowControl_MouseWheel(sender, e);
            }
        }

        private void HSmartWindowControl1_MouseWheel(object sender, MouseEventArgs e)
        {
            //HSmartWindowControl控件的区域
            Rectangle rect = hSmartWindowControl1.RectangleToScreen(hSmartWindowControl1.ClientRectangle);
            //滚动时，鼠标悬停在在HSmartWindowControl控件上
            if (rect.Contains(System.Windows.Forms.Cursor.Position))
            {
                //缩放
                hSmartWindowControl1.HSmartWindowControl_MouseWheel(sender, e);
            }
        }

        private void HSmartWindowControl5_MouseWheel(object sender, MouseEventArgs e)
        {
            //HSmartWindowControl控件的区域
            Rectangle rect = hSmartWindowControl5.RectangleToScreen(hSmartWindowControl5.ClientRectangle);
            //滚动时，鼠标悬停在在HSmartWindowControl控件上
            if (rect.Contains(System.Windows.Forms.Cursor.Position))
            {
                //缩放
                hSmartWindowControl5.HSmartWindowControl_MouseWheel(sender, e);
            }
        }

        private void initPLC()
        {
            tool.ReadConfigFile();
            if (configfil.PLCIpAddress != null && configfil.PLCPort != 0)
            {
                PLC.IpAddress = configfil.PLCIpAddress;
                PLC.Port = configfil.PLCPort;
                operateResult = PLC.ConnectServer();
                if (operateResult.IsSuccess == false)
                {
                    MessageBox.Show("PLC连接失败");
                    toolStripStatusLabel2.Text = "未连接";
                    toolStripStatusLabel2.BackColor = Color.Red;
                }
                else
                {
                    toolStripStatusLabel2.Text = "已连接";
                    PLC_Connection = true;
                    toolStripStatusLabel2.BackColor = Color.Green;
                    Task PLC_task = new Task(GetPLC_State);
                    PLC_task.Start();
                    Task PLC_task1 = new Task(() =>
                    {
                        while (operateResult.IsSuccess)
                        {
                            PLC.Write("R0", (short)1);
                            Thread.Sleep(50);
                        }

                    });
                    PLC_task1.Start();
                    //左轴参数
                    textBox55.Text = (PLC.ReadInt32("R154").Content / 1000).ToString();
                    textBox57.Text = (PLC.ReadInt32("R156").Content / 1000).ToString();
                    textBox59.Text = (PLC.ReadInt32("R158").Content / 1000).ToString();
                    //PIN孔位置
                    textBox61.Text = (PLC.ReadInt32("R160").Content / 1000).ToString();
                    textBox63.Text = (PLC.ReadInt32("R162").Content / 1000).ToString();

                    textBox56.Text = (PLC.ReadInt32("R104").Content / 1000).ToString();
                    textBox58.Text = (PLC.ReadInt32("R106").Content / 1000).ToString();
                    textBox60.Text = (PLC.ReadInt32("R108").Content / 1000).ToString();
                    textBox62.Text = (PLC.ReadInt32("R110").Content / 1000).ToString();
                    textBox64.Text = (PLC.ReadInt32("R112").Content / 1000).ToString();
                    //右轴参数
                    textBox65.Text = (PLC.ReadInt32("R254").Content / 1000).ToString();
                    textBox66.Text = (PLC.ReadInt32("R256").Content / 1000).ToString();
                    textBox68.Text = (PLC.ReadInt32("R258").Content / 1000).ToString();
                    //PIN孔位置
                    textBox69.Text = (PLC.ReadInt32("R260").Content / 1000).ToString();
                    textBox71.Text = (PLC.ReadInt32("R262").Content / 1000).ToString();

                    textBox67.Text = (PLC.ReadInt32("R204").Content / 1000).ToString();
                    textBox70.Text = (PLC.ReadInt32("R206").Content / 1000).ToString();
                    textBox72.Text = (PLC.ReadInt32("R208").Content / 1000).ToString();
                    textBox73.Text = (PLC.ReadInt32("R210").Content / 1000).ToString();
                    textBox74.Text = (PLC.ReadInt32("R212").Content / 1000).ToString();
                    if (productList.Product_list[Now_Product_ID].Pinchek == true)
                    {
                        if (productList.Product_list[Now_Product_ID].LeftPinchekPos != "")
                        {
                            PLC.Write("R160", (Convert.ToInt32(productList.Product_list[Now_Product_ID].LeftPinchekPos) * 1000));
                        }
                        if (productList.Product_list[Now_Product_ID].RightPinchekPos != "")
                        {
                            PLC.Write("R260", (Convert.ToInt32(productList.Product_list[Now_Product_ID].RightPinchekPos) * 1000));
                        }

                    }
                }
            }
            else
            {
                toolStripStatusLabel2.Text = "未连接";
                toolStripStatusLabel2.BackColor = Color.Red;
                MessageBox.Show("PLC连接异常！");
            }
        }
        /// <summary>
        /// PLC工作线程
        /// </summary>
        private void GetPLC_State()
        {
            DisplayTxt(richTextBox1, "等待PLC触发拍照");
            while (operateResult.IsSuccess)
            {

                EndMinLeftHikCamera = PLC.ReadInt16(configfil.MinEnd_Left).Content;
                EndMinRightHikCamera = PLC.ReadInt16(configfil.MinEnd_Right).Content;
                StartMinLeftHikCamera = PLC.ReadInt16(configfil.MinStartLeft).Content;
                StartMinRightHikCamera = PLC.ReadInt16(configfil.MinStartRight).Content;

                if (StartMinLeftHikCamera == 1)
                {
                    if (checkBox2.Checked == true)
                    {
                        Thread.Sleep(500);
                        hSmartWindowControl3.HalconWindow.ClearWindow();
                        Bitmap HikgetimageL = null;
                        HikgetimageL = HikLeftCamera.GetImageBitMap();
                        ImageConvert.Bitmap2HObjectS(HikgetimageL, out HObject Hikgetimagel);
                        PLC.Write(configfil.MinStartLeft, 2);
                        DisplayTxt(richTextBox1, "左PIN孔获取一张图像");

                        try
                        {
                            if (productList.Product_list[Now_Product_ID].HikStandraModel_Path != " ")
                            {
                                Measure_Tool measure_Tool = new Measure_Tool();
                                PinCheck pincheck = new PinCheck();
                                HOperatorSet.GetImageSize(Hikgetimagel, out manualImage_width, out manualImage_Height);
                                HOperatorSet.SetPart(hSmartWindowControl3.HalconWindow, 0, 0, manualImage_Height - 1, manualImage_width - 1);
                                HOperatorSet.DispObj(Hikgetimagel, hSmartWindowControl3.HalconWindow);
                                hSmartWindowControl3.SetFullImagePart();

                                HOperatorSet.ReadRegion(out HObject Region, productList.Product_list[Now_Product_ID].HikStandraModel_Path);
                                for (int i = 0; i < productList.Product_list[Now_Product_ID].MeasureList.Count; i++)
                                {
                                    if (productList.Product_list[Now_Product_ID].MeasureList[i].PinName != "")
                                    {
                                        pincheck = productList.Product_list[Now_Product_ID].MeasureList[i].MeasurePin(hSmartWindowControl3, Hikgetimagel, Region, HikLeftCameraParam, HikLeftPose,"Left");
                                    }
                                    LeftPinStationMeasureResult = pincheck;
                                }
                                if (checkBox6.Checked == false)
                                {
                                    if (pincheck.TestReult == false)
                                    {
                                        PLC.Write(configfil.MinTestReult_Left, 2);
                                        HOperatorSet.DispText(hSmartWindowControl3.HalconWindow, "NG", "image", 0, 0, "red", "box", "false");
                                        DisplayTxt(richTextBox1, "左PIN孔回复PLC NG");
                                        SaveImageTestReultPIN = "NG";
                                    }
                                    else
                                    {
                                        PLC.Write(configfil.MinTestReult_Left, 1);
                                        HOperatorSet.DispText(hSmartWindowControl3.HalconWindow, "OK", "image", 0, 0, "green", "box", "false");
                                        DisplayTxt(richTextBox1, "左PIN孔回复PLC OK");
                                        SaveImageTestReultPIN = "OK";
                                    }
                                }
                                else
                                {
                                    PLC.Write(configfil.MinTestReult_Left, 1);
                                    HOperatorSet.DispText(hSmartWindowControl3.HalconWindow, "OK", "image", 0, 0, "green", "box", "false");
                                    DisplayTxt(richTextBox1, "左PIN孔回复PLC OK");
                                    SaveImageTestReultPIN = "OK";
                                }
                                isLeftPinStatus = true;
                               // Debug.WriteLine(DateTime.Now.ToString("pin"+ "yyyy/MM/dd HH:mm:ss fff"));
                                this.Invoke(new Action(() =>
                                {
                                    try
                                    {
                                        dataGridView3.Rows.Clear();
                                        dataGridView3.Rows.Add(new DataGridViewRow());
                                        dataGridView3.Rows.Add(new DataGridViewRow());
                                        dataGridView3.Rows[0].Cells[0].Value = 1;//序号
                                        dataGridView3.Rows[1].Cells[0].Value = 2;//序号
                                        dataGridView3.Rows[0].Cells[1].Value = "孔 1";//测量名称
                                        dataGridView3.Rows[1].Cells[1].Value = "孔 2";//测量名称
                                        //长
                                        dataGridView3.Rows[0].Cells[2].Value = pincheck.Height.ToString("f2");
                                        dataGridView3.Rows[1].Cells[2].Value = pincheck.Height1.ToString("f2");
                                        //宽
                                        dataGridView3.Rows[0].Cells[3].Value = pincheck.Width.ToString("f2");
                                        dataGridView3.Rows[1].Cells[3].Value = pincheck.Width1.ToString("f2");
                                        //X
                                        dataGridView3.Rows[0].Cells[4].Value = pincheck.Row.ToString("f2");
                                        dataGridView3.Rows[1].Cells[4].Value = pincheck.Row1.ToString("f2");
                                        //Y
                                        dataGridView3.Rows[0].Cells[5].Value = pincheck.Column.ToString("f2");
                                        dataGridView3.Rows[1].Cells[5].Value = pincheck.Column1.ToString("f2");
                                        //NG行的背景颜色设置为红色
                                        if (pincheck.TestReult == false)
                                        {
                                            dataGridView3.Rows[0].DefaultCellStyle.BackColor = Color.Red;
                                        }
                                        if (pincheck.TestReult1 == false)
                                        {
                                            dataGridView3.Rows[1].DefaultCellStyle.BackColor = Color.Red;
                                        }

                                    }
                                    catch (Exception ex)
                                    {
                                    }
                                }));
                            }
                            else
                            {
                                PLC.Write(configfil.MinTestReult_Left, 2);
                                isLeftPinStatus = true;
                            }
                        }
                        catch (Exception ex)
                        {
                            PLC.Write(configfil.MinStartLeft, 2);
                            PLC.Write(configfil.MinTestReult_Left, 2);
                            DisplayTxt(richTextBox1, "左侧Pin孔检测失败");
                            isLeftPinStatus = true;
                        }
                        if (SaveImagecheck == true)
                        {
                            Task task = Task.Run(() => SaveImages("HIKCamera", Hikgetimagel, "HikCamerLeft", SaveImageTestReultPIN, LeftStationCode));
                        }
                    }
                    else
                    {
                        PLC.Write(configfil.MinStartLeft, 2);
                        PLC.Write(configfil.MinTestReult_Left, 1);
                    }
                }
                if (StartMinRightHikCamera == 1)
                {

                    if (checkBox2.Checked == true)
                    {
                        Thread.Sleep(500);
                        hSmartWindowControl4.HalconWindow.ClearWindow();
                        Bitmap HikgetimageR = null;
                        HikgetimageR = HikRightCamera.GetImageBitMap();
                        ImageConvert.Bitmap2HObjectS(HikgetimageR, out HObject Hikgetimager);
                        PLC.Write(configfil.MinStartRight, 2);
                        DisplayTxt(richTextBox1, "右PIN孔获取一张图像");


                        try
                        {
                            if (productList.Product_list[Now_Product_ID].HikStandraModel_Path != " ")
                            {
                                Measure_Tool measure_Tool = new Measure_Tool();
                                PinCheck pincheck = new PinCheck();
                                HOperatorSet.GetImageSize(Hikgetimager, out manualImage_width, out manualImage_Height);
                                HOperatorSet.SetPart(hSmartWindowControl4.HalconWindow, 0, 0, manualImage_Height - 1, manualImage_width - 1);
                                HOperatorSet.DispObj(Hikgetimager, hSmartWindowControl4.HalconWindow);
                                hSmartWindowControl4.SetFullImagePart();

                                HOperatorSet.ReadRegion(out HObject Region, productList.Product_list[Now_Product_ID].HikStandraModel_Path);
                                for (int i = 0; i < productList.Product_list[Now_Product_ID].MeasureList.Count; i++)
                                {
                                    if (productList.Product_list[Now_Product_ID].MeasureList[i].PinName != "")
                                    {
                                        pincheck = productList.Product_list[Now_Product_ID].MeasureList[i].MeasurePin(hSmartWindowControl4, Hikgetimager, Region, HikRightCameraParam, HikRightPose,"Right");
                                        RightPinStationMeasureResult = pincheck;
                                    }
                                }
                                if (checkBox6.Checked == false)
                                {
                                    if (pincheck.TestReult == false || pincheck.TestReult1 == false)
                                    {
                                        HOperatorSet.DispText(hSmartWindowControl4.HalconWindow, "NG", "image", 0, 0, "red", "box", "false");
                                        PLC.Write(configfil.MinTestReult_Right, 2);
                                        DisplayTxt(richTextBox1, "右PIN孔回复PLC NG");
                                        SaveImageTestReultPIN = "NG";
                                    }
                                    else
                                    {
                                        HOperatorSet.DispText(hSmartWindowControl4.HalconWindow, "OK", "image", 0, 0, "green", "box", "false");
                                        PLC.Write(configfil.MinTestReult_Right, 1);
                                        DisplayTxt(richTextBox1, "右PIN孔回复PLC OK");
                                        SaveImageTestReultPIN = "OK";
                                    }
                                }
                                else
                                {
                                    HOperatorSet.DispText(hSmartWindowControl4.HalconWindow, "OK", "image", 0, 0, "green", "box", "false");
                                    PLC.Write(configfil.MinTestReult_Right, 1);
                                    DisplayTxt(richTextBox1, "右PIN孔回复PLC OK");
                                    SaveImageTestReultPIN = "OK";
                                }
                                isRightPinStatus = true;
                                this.Invoke(new Action(() =>
                                {
                                    try
                                    {
                                        dataGridView4.Rows.Clear();
                                        dataGridView4.Rows.Add(new DataGridViewRow());
                                        dataGridView4.Rows.Add(new DataGridViewRow());
                                        dataGridView4.Rows[0].Cells[0].Value = 1;//序号
                                    dataGridView4.Rows[1].Cells[0].Value = 2;//序号
                                    dataGridView4.Rows[0].Cells[1].Value = "孔 1";//测量名称
                                    dataGridView4.Rows[1].Cells[1].Value = "孔 2";//测量名称
                                                                                 //长
                                    dataGridView4.Rows[0].Cells[2].Value = pincheck.Height.ToString("f2");
                                        dataGridView4.Rows[1].Cells[2].Value = pincheck.Height1.ToString("f2");
                                    //宽
                                    dataGridView4.Rows[0].Cells[3].Value = pincheck.Width.ToString("f2");
                                        dataGridView4.Rows[1].Cells[3].Value = pincheck.Width1.ToString("f2");
                                    //X
                                    dataGridView4.Rows[0].Cells[4].Value = pincheck.Row.ToString("f2");
                                        dataGridView4.Rows[1].Cells[4].Value = pincheck.Row1.ToString("f2");
                                    //Y
                                    dataGridView4.Rows[0].Cells[5].Value = pincheck.Column.ToString("f2");
                                        dataGridView4.Rows[1].Cells[5].Value = pincheck.Column1.ToString("f2");
                                    //NG行的背景颜色设置为红色
                                    if (pincheck.TestReult == false)
                                        {
                                            dataGridView4.Rows[0].DefaultCellStyle.BackColor = Color.Red;
                                        }
                                        if (pincheck.TestReult1 == false)
                                        {
                                            dataGridView4.Rows[1].DefaultCellStyle.BackColor = Color.Red;
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                    }
                                }));
                            }
                            else
                            {
                                PLC.Write(configfil.MinTestReult_Right, 2);
                                isRightPinStatus = true;
                            }

                        }
                        catch (Exception ex)
                        {
                            PLC.Write(configfil.MinStartRight, 2);
                            PLC.Write(configfil.MinTestReult_Right, 2);
                            DisplayTxt(richTextBox1, "右侧Pin孔检测失败");
                            isRightPinStatus = true;
                        }
                        
                        if (SaveImagecheck == true)
                        {
                            Task task = Task.Run(() => SaveImages("HIKCamera", Hikgetimager, "HikCamerRight", SaveImageTestReultPIN, RightStationCode));
                        }

                    }
                    else
                    {
                        PLC.Write(configfil.MinStartRight, 2);
                        PLC.Write(configfil.MinTestReult_Right, 1);

                    }
                }
                Thread.Sleep(50);
            }
        }
        private void CloseCamera()
        {
            HikLeftCamera.Close();
            HikRightCamera.Close();
            IKapBoard.IKapStopGrab(camera.m_hBoardL);
            IKapBoard.IKapStopGrab(camera.m_hBoardR);
            camera.UnRegisterCallback();
            camera.CloseDevice();
            camera.ReleaseEnvironment();

        }

        private Feature FindFeature(string FeatureName)
        {
            Feature feature = new Feature();
            if (productList.Product_list[Now_Product_ID].FeaturesList.Count > 0)
            {
                for (int i = 0; i < productList.Product_list[Now_Product_ID].FeaturesList.Count; i++)
                {
                    if (productList.Product_list[Now_Product_ID].FeaturesList[i].Name == FeatureName)
                    {
                        feature = productList.Product_list[Now_Product_ID].FeaturesList[i];
                        break;
                    }
                }
            }

            return feature;
        }
        private void Form1_Shown(object sender, EventArgs e)
        {
            // 读取标定文件
            HOperatorSet.ReadTuple(Directory.GetCurrentDirectory() + "//Config//Camera_Left", out Calibration_CameraLeft);
            HOperatorSet.ReadTuple(Directory.GetCurrentDirectory() + "//Config//Camera_Right", out Calibration_CameraRight);
            HOperatorSet.ReadPose(Directory.GetCurrentDirectory() + "//Config//rightWC.dat", out HikRightPose);
            HOperatorSet.ReadCamPar(Directory.GetCurrentDirectory() + "//Config//rightNC.cal", out HikRightCameraParam);
            HOperatorSet.ReadPose(Directory.GetCurrentDirectory() + "//Config//leftWC.dat", out HikLeftPose);
            HOperatorSet.ReadCamPar(Directory.GetCurrentDirectory() + "//Config//leftNC.cal", out HikLeftCameraParam);
            HikVisionCamera.InitCameraList();
            camera.InitEnvironment();
            ConnectCameras(false);
            Configurationfile = camera.ConfigureFrameGrabber(OnFrameReadyFuncL, false, configfil.SerialNumberL, "Left");
            Configurationfile = camera.ConfigureFrameGrabber(OnFrameReadyFuncR, false, configfil.SerialNumberR, "Right");
            if (Configurationfile == true)
            {
                DisplayTxt(richTextBox1, "配置文件 " + configfil.LeftConfigurationfilepath + "  已打开");
                DisplayTxt(richTextBox1, "配置文件 " + configfil.RightConfigurationfilepath + "  已打开");
            }
            else
            {
                DisplayTxt(richTextBox1, "配置文件 " + configfil.LeftConfigurationfilepath + "  打开异常");
                DisplayTxt(richTextBox1, "配置文件 " + configfil.RightConfigurationfilepath + "  打开异常");
            }
            camera.SetFrameTrigger();
            ReadConfigfilState();
            IKapBoard.IKapStartGrab(camera.m_hBoardL, Collection_method);
            IKapBoard.IKapStartGrab(camera.m_hBoardR, Collection_method);
            initPLC();
        }
        private int Find_Now_ID(ProductList productList)
        {
            int Id = 0;
            if (productList.Product_list.Count > 0)
            {
                for (int i = 0; i < productList.Product_list.Count; i++)
                {
                    if (productList.Product_list[i].ProductName == productList.Product_Now) Id = i;
                }
            }
            return Id;
        }
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            
            if (MessageBox.Show("是否关闭软件", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button2) == DialogResult.No)
            {
                e.Cancel = true;
                return;
            }
            CloseCamera();
            tool.SaveConfigFile(configfil);
            tool.SaveProductFile(productList);

        }
        private void ConnectCameras(bool Manual_control)
        {
            configfil = tool.ReadConfigFile();
            uint DevCount = camera.detectDevice(Manual_control);
            if (DevCount != 0)
            {
                camera.JudgeCameraSerialNumber(configfil.SerialNumberL, "Left");
                camera.JudgeCameraSerialNumber(configfil.SerialNumberR, "Right");

                DisplayTxt(richTextBox1, "连接埃科相机：" + configfil.SerialNumberL + "  成功");
                DisplayTxt(richTextBox1, "连接埃科相机：" + configfil.SerialNumberR + "  成功");
            }
            else
            {
                DisplayTxt(richTextBox1, "埃科左线扫相机打开异常");
                DisplayTxt(richTextBox1, "埃科右线扫相机打开异常");
            }
            if (HikLeftCamera.Open_Dev(configfil.HikLeftCameraSeria) != 0)
            {
                DisplayTxt(richTextBox1, "海康左相机打开异常");
            }
            else
            {
                DisplayTxt(richTextBox1, "海康左相机已打开");
                HikLeftCamera.m_MyCamera.SetFloatValue("ExposureTime", configfil.HikLeftCameraExposureTime);
                comboBox1.Items.Add("海康左" + configfil.HikLeftCameraSeria);
            }
            if (HikRightCamera.Open_Dev(configfil.HikRightCameraSeria) != 0)
            {
                DisplayTxt(richTextBox1, "海康右相机打开异常");
            }
            else
            {
                DisplayTxt(richTextBox1, "海康右相机已打开");
                HikRightCamera.m_MyCamera.SetFloatValue("ExposureTime", configfil.HikRightCameraExposureTime);
                comboBox1.Items.Add("海康右" + configfil.HikRightCameraSeria);
            }
        }
        /// <summary>
        /// 读取保存参数
        /// </summary>
        private void ReadConfigfilState()
        {
            if (File.Exists(Directory.GetCurrentDirectory() + @"\Config\ProductList.json") == true)
            {
                FileStream fileStream1 = new FileStream(Directory.GetCurrentDirectory() + @"\Config\ProductList.json", FileMode.Open, FileAccess.Read);
                StreamReader streamReader1 = new StreamReader(fileStream1, Encoding.Default);
                string Json_Config = streamReader1.ReadToEnd();
                streamReader1.Close();
                fileStream1.Close();
                productList = JsonConvert.DeserializeObject<ProductList>(Json_Config);
                if (productList.Product_list.Count > 0)
                {
                    for (int i = 0; i < productList.Product_list.Count; i++)
                    {

                        comboBox2.Items.Add(productList.Product_list[i].ProductName);
                    }
                }

                Now_Product_ID = Find_Now_ID(productList);
                label54.Text = productList.Product_Now;
                if (Now_Product_ID > -1) comboBox2.SelectedIndex = Now_Product_ID;


                if (productList.Product_list[Now_Product_ID].FeaturesList.Count > 0)
                {
                    for (int i = 0; i < productList.Product_list[Now_Product_ID].FeaturesList.Count; i++)
                    {
                        listBox1.Items.Add(productList.Product_list[Now_Product_ID].FeaturesList[i].Name);
                    }
                }
                if (productList.Product_list[Now_Product_ID].HikProductName != " ")
                {
                    listBox8.Items.Add(productList.Product_list[Now_Product_ID].HikProductName);
                }
                if (productList.Product_list[Now_Product_ID].Pinchek == true)
                {
                    checkBox2.Checked = true;
                }
                if (productList.Product_list[Now_Product_ID].MeasureList.Count > 0)
                {
                    for (int i = 0; i < productList.Product_list[Now_Product_ID].MeasureList.Count; i++)
                    {

                        if (productList.Product_list[Now_Product_ID].MeasureList[i].Name != "")
                        {
                            listBox2.Items.Add(productList.Product_list[Now_Product_ID].MeasureList[i].Name);
                        }
                        if (productList.Product_list[Now_Product_ID].MeasureList[i].PinName != "")
                        {
                            listBox2.Items.Add(productList.Product_list[Now_Product_ID].MeasureList[i].PinName);
                        }
                    }
                }
            }
            textBox45.Text = configfil.Left_Scaled.ToString();
            textBox46.Text = configfil.Right_Scaled.ToString();
            comboBox3.SelectedIndex = 0;

            configfil = tool.ReadConfigFile();
            if (configfil.SaveImagePath != null)
            {
                textBox3.Text = configfil.SaveImagePath;
            }

            textBox2.Text = configfil.LeftCameraConfigepath;
            textBox20.Text = configfil.RightCameraConfigepath;
            textBox4.Text = configfil.LeftConfigurationfilepath;
            textBox26.Text = configfil.RightConfigurationfilepath;
            SaveImagecheck = configfil.SaveImageCheck;
            checkBox1.Checked = configfil.SaveImageCheck;

            textBox86.Text = configfil.MesSavePath;

            textBox5.Text = configfil.HikLeftCameraSeria;
            textBox23.Text = configfil.HikRightCameraSeria;

            textBox24.Text = configfil.SerialNumberL;
            textBox25.Text = configfil.SerialNumberR;
            //PLC参数读取
            textBox7.Text = configfil.StartLeft;
            textBox8.Text = configfil.End_Left;
            textBox9.Text = configfil.TestCodeReading_Left;
            textBox10.Text = configfil.TestMeasurement_Left;
            textBox11.Text = configfil.TestReult_Left;

            textBox14.Text = configfil.StartRight;
            textBox15.Text = configfil.End_Right;
            textBox16.Text = configfil.TestCodeReading_Right;
            textBox17.Text = configfil.TestMeasurement_Right;
            textBox18.Text = configfil.TestReult_Right;

            textBox12.Text = configfil.MinStartLeft;
            textBox19.Text = configfil.MinTestReult_Left;

            textBox21.Text = configfil.MinStartRight;
            textBox22.Text = configfil.MinTestReult_Right;

            textBox13.Text = configfil.PLCIpAddress;
            textBox6.Text = configfil.PLCPort.ToString();

            productList.Product_list[Now_Product_ID].CalibrationLineList.Clear();
            Measure_record = true;
        }
        /// <summary>
        /// 保存图像
        /// </summary>
        private void SaveImages(string CameraProduct, HObject image, string Local,string TestReult, string StationCode)
        {
            if (SaveImagecheck == true)
            {
                if (StationCode=="")
                {
                    StationCode = ImageNumber.ToString();
                }
                if (TestReult=="")
                {
                    TestReult = "NG";
                }
                if (Directory.Exists(configfil.SaveImagePath + "\\" + CameraProduct + "\\" + DateTime.Now.ToString("yyyyMMdd") + "\\" + TestReult + "\\" + Local) == false)
                {
                    Directory.CreateDirectory(configfil.SaveImagePath + "\\" + CameraProduct + "\\" + DateTime.Now.ToString("yyyyMMdd") + "\\" + TestReult + "\\" + Local);
                }
                string SaveImagePath = configfil.SaveImagePath + "\\" + CameraProduct + "\\" + DateTime.Now.ToString("yyyyMMdd") + "\\" + TestReult + "\\" + Local + "\\" + StationCode + ".bmp";
                HOperatorSet.WriteImage(image, "bmp", 0, SaveImagePath);
            }
            return;
        }
        private void SaveImages(string CameraProduct, Bitmap image, string Local, string TestReult, string StationCode)
        {
            if (SaveImagecheck == true)
            {

                if (Directory.Exists(configfil.SaveImagePath + "\\" + CameraProduct + "\\" + DateTime.Now.ToString("yyyyMMdd") + "\\" + TestReult + "\\" + Local) == false)
                {
                    Directory.CreateDirectory(configfil.SaveImagePath + "\\" + CameraProduct + "\\" + DateTime.Now.ToString("yyyyMMdd") + "\\" + TestReult + "\\" + Local);
                }
                string SaveImagePath = configfil.SaveImagePath + "\\" + CameraProduct + "\\" + DateTime.Now.ToString("yyyyMMdd") + "\\" + TestReult + "\\" + Local + "\\" + StationCode + ".bmp";
                image.Save(SaveImagePath, System.Drawing.Imaging.ImageFormat.Bmp);

            }
            return;
        }
        //测试
        public void Test()
        {
            HOperatorSet.ReadImage(out HObject Images, @"C:\Users\admin\Desktop\NG\LineScanLeft\8SSB11N51748X3XP4BL004Y.bmp");

            Debug.WriteLine("开始检测： " + DateTime.Now.ToString("yyyy/MM/dd HH-mm-ss:ff"));

            HOperatorSet.GetImageSize(Images, out manualImage_width, out manualImage_Height);
            HOperatorSet.SetPart(hSmartWindowControl1.HalconWindow, 0, 0, manualImage_Height - 1, manualImage_width - 1);
            HOperatorSet.DispObj(Images, hSmartWindowControl1.HalconWindow);
            hSmartWindowControl1.SetFullImagePart();
            bool Is_Model1 = File.Exists(productList.Product_list[Now_Product_ID].StandraModel_Path1);
            bool Is_Model2 = File.Exists(productList.Product_list[Now_Product_ID].StandraModel_Path2);
            string temp_code = "";
            if (Is_Model1 == true && Is_Model2 == true)
            {
                Measure measure = new Measure(manualImage_width, manualImage_Height);
                HOperatorSet.ReadShapeModel(productList.Product_list[Now_Product_ID].StandraModel_Path1, out HTuple ModelID1);
                HOperatorSet.ReadShapeModel(productList.Product_list[Now_Product_ID].StandraModel_Path2, out HTuple ModelID2);
                Algorithm.Create_Stanrad_Point(Images, out HObject RegionLine, out HObject Circle_Region, ModelID1, ModelID2, out HTuple Row, out HTuple Column, out HTuple Angle);
                Debug.WriteLine("查找模型完成： " + DateTime.Now.ToString("yyyy/MM/dd HH-mm-ss:ff"));
                double Rotation_Center = Angle.D - productList.Product_list[Now_Product_ID].Standard_Angle;
                if (Rotation_Center > 3) Rotation_Center = Rotation_Center - Math.PI;
                if (Rotation_Center < -3) Rotation_Center = Rotation_Center + Math.PI;

                HOperatorSet.VectorAngleToRigid(productList.Product_list[Now_Product_ID].Standard_Row, productList.Product_list[Now_Product_ID].Standard_Column, 0, Row, Column, Rotation_Center, out HTuple HomMat2DTranslate);
                List<LineAndRecangelResult> lineAndRecangelResults = new List<LineAndRecangelResult>();
                string path = "";
                for (int i = 0; i < productList.Product_list[Now_Product_ID].FeaturesList.Count; i++)
                {
                    path = productList.Product_list[Now_Product_ID].FeaturesList[i].Region_Path;
                    if (File.Exists(path))
                    {
                        measure.GetResult(hSmartWindowControl1, productList.Product_list[Now_Product_ID].FeaturesList[i], Images, HomMat2DTranslate, path, lineAndRecangelResults);
                    }
                    // LeftStationMeasureResult.Add(productList.Product_list[Now_Product_ID].MeasureList[i].Measure_Tool_Run(hSmartWindowControl1, Images, manualImage_width, manualImage_Height, HomMat2DTranslate, Calibration_CameraLeft, ref temp_code, configfil.Left_Scaled));

                }
                //计算轴线
                Feature feature1 = productList.Product_list[Now_Product_ID].FeaturesList.Find(x => x.Name.Contains("基准轴") && x.Name.Contains(","));
                Feature feature2 = productList.Product_list[Now_Product_ID].FeaturesList.Find(x => x.Name.Contains("基准轴") && !x.Name.Contains(","));
                //基准轴线
                string pointName1 = feature1.Name.Split('_')[1].Split(',')[0];
                string pointName2 = feature1.Name.Split('_')[1].Split(',')[1];
                double startRow1 = lineAndRecangelResults.Find(x => x.name == pointName1).centerRow;
                double startCol1 = lineAndRecangelResults.Find(x => x.name == pointName1).centerCol;
                double endRow1 = lineAndRecangelResults.Find(x => x.name == pointName2).centerRow;
                double endCol1 = lineAndRecangelResults.Find(x => x.name == pointName2).centerCol;
                lineAndRecangelResults.Add(new LineAndRecangelResult() { name = feature1.Name, startRow = startRow1, startCol = startCol1, endRow = endRow1, endCol = endCol1 });
                HOperatorSet.GenRegionLine(out HObject regionline1, startRow1, startCol1, endRow1, endCol1);
                HOperatorSet.DispObj(regionline1, hSmartWindowControl1.HalconWindow);
                //投影轴线
                string pointName3 = feature2.Name.Split('_')[1];
                double startRow3 = lineAndRecangelResults.Find(x => x.name == pointName3).centerRow;
                double startCol3 = lineAndRecangelResults.Find(x => x.name == pointName3).centerCol;
                HOperatorSet.ProjectionPl(startRow3, startCol3, startRow1, startCol1, endRow1, endCol1, out HTuple rowProj, out HTuple colProj);
                lineAndRecangelResults.Add(new LineAndRecangelResult() { name = feature2.Name, startRow = startRow3, startCol = startCol3, endRow = rowProj, endCol = colProj });

                //计算点构线
                Feature feature3 = productList.Product_list[Now_Product_ID].FeaturesList.Find(x => x.Name.Contains("点构线") && x.Name.Contains(","));
                //点构线
                string pointName4 = feature3.Name.Split('_')[1].Split(',')[0];
                string pointName5 = feature3.Name.Split('_')[1].Split(',')[1];
                double startRow = lineAndRecangelResults.Find(x => x.name == pointName4).centerRow;
                double startCol = lineAndRecangelResults.Find(x => x.name == pointName4).centerCol;
                double endRow = lineAndRecangelResults.Find(x => x.name == pointName5).centerRow;
                double endCol = lineAndRecangelResults.Find(x => x.name == pointName5).centerCol;
                lineAndRecangelResults.Add(new LineAndRecangelResult() { name = feature3.Name, startRow = startRow, startCol = startCol, endRow = endRow, endCol = endCol });
                HOperatorSet.GenRegionLine(out HObject regionline, startRow, startCol, endRow, endCol);
                HOperatorSet.DispObj(regionline, hSmartWindowControl1.HalconWindow);
                
                Debug.WriteLine("特征提取已完成： " + DateTime.Now.ToString("yyyy/MM/dd HH-mm-ss:ff"));
                for (int i = 0; i < productList.Product_list[Now_Product_ID].MeasureList.Count; i++)
                {
                    LeftStationMeasureResult.Add(productList.Product_list[Now_Product_ID].MeasureList[i].Measure_Tool_Run(hSmartWindowControl1, Images, manualImage_width, manualImage_Height, HomMat2DTranslate, Calibration_CameraLeft, ref temp_code, configfil.Left_Scaled, lineAndRecangelResults,"Left"));

                }
                Debug.WriteLine("尺寸测量完成： " + DateTime.Now.ToString("yyyy/MM/dd HH-mm-ss:ff"));
                HOperatorSet.DumpWindowImage(out HObject image, hSmartWindowControl1.HalconWindow);
                HOperatorSet.DispObj(image, hSmartWindowControl2.HalconWindow);
                //HOperatorSet.WriteImage(image, "bmp", 0, @"C:\Users\admin\Desktop\ceshi\" + DateTime.Now.ToString() + ".bmp");
            }
        }
        
        /// <summary>
        /// 图像获取
        /// </summary>
        /// <param name="pParam"></param>
        public void OnFrameReadyFuncL(IntPtr pParam)
        {
            DisplayTxt(richTextBox1, "左接收到触发信号");
            Console.WriteLine("Grab frame ready");
            IntPtr hDev = (IntPtr)pParam;
            IntPtr pUserBuffer = IntPtr.Zero;
            int nFrameSize = 0;
            int nFrameCount = 0;
            int width = 0, height = 0, nDepth = 0, nChannels = 0, nImageType = 0;
            IKapBoard.IKAPBUFFERSTATUS status = new IKapBoard.IKAPBUFFERSTATUS();
            try
            {
                IKapBoard.IKapGetInfo(hDev, (uint)INFO_ID.IKP_FRAME_COUNT, ref nFrameCount);
                IKapBoard.IKapGetBufferStatus(hDev, camera.m_nCurFrameIndexL, ref status);
            }
            catch (Exception ex)
            {
                DisplayTxt(richTextBox1, "左 IKapBoard 错误：" + ex);

            }


            // 当图像缓冲区满时。
            //
            // When the buffer is full.
            if (status.uFull == 1)
            {
                // 获取一帧图像的大小。
                //
                // Get the size of a frame of image.
                IKapBoard.IKapGetInfo(hDev, (uint)INFO_ID.IKP_FRAME_SIZE, ref nFrameSize);
                IKapBoard.IKapGetInfo(camera.m_hBoardL, (uint)INFO_ID.IKP_IMAGE_WIDTH, ref width);
                IKapBoard.IKapGetInfo(camera.m_hBoardL, (uint)INFO_ID.IKP_IMAGE_HEIGHT, ref height);
                IKapBoard.IKapGetInfo(camera.m_hBoardL, (uint)INFO_ID.IKP_DATA_FORMAT, ref nDepth);
                IKapBoard.IKapGetInfo(camera.m_hBoardL, (uint)INFO_ID.IKP_IMAGE_TYPE, ref nImageType);
                switch (nImageType)
                {
                    case 0:
                        nChannels = 1;
                        break;
                    case 1:
                    case 3:
                        nChannels = 3;
                        break;
                    case 2:
                    case 4:
                        nChannels = 4;
                        break;
                }

                // 获取缓冲区地址。
                //
                // Get the buffer address.
                IKapBoard.IKapGetBufferAddress(hDev, camera.m_nCurFrameIndexL, ref pUserBuffer);
                //图像转换
                //buffertoimg = new BufferToImage(nFrameSize, nDepth, nChannels, width, height);
                //Bitmap bitmap = (Bitmap)buffertoimg.toImage(pUserBuffer);

                DisplayTxt(richTextBox1, "左获取一张图像");
                HOperatorSet.GenImage1Extern(out HObject Images, "byte", width, height, pUserBuffer, IntPtr.Zero);
                string temp_code = "";
                LeftStationMeasureResult.Clear();
                MesJudgeL = "PASS";
                 CsvTestReult = "OK";
                HOperatorSet.GetImageSize(Images, out manualImage_width, out manualImage_Height);
                HOperatorSet.SetPart(hSmartWindowControl1.HalconWindow, 0, 0, manualImage_Height - 1, manualImage_width - 1);
                HOperatorSet.DispObj(Images, hSmartWindowControl1.HalconWindow);
                hSmartWindowControl1.SetFullImagePart();
                HOperatorSet.SetFont(hSmartWindowControl1.HalconWindow, "default-Normal-12");

                if (File.Exists(productList.Product_list[Now_Product_ID].StandraModel_Path1) == true)
                {
                    bool Is_Model1 = File.Exists(productList.Product_list[Now_Product_ID].StandraModel_Path1);
                    bool Is_Model2 = File.Exists(productList.Product_list[Now_Product_ID].StandraModel_Path2);
                    bool Is_ModelRegion1 = File.Exists(productList.Product_list[Now_Product_ID].ModelRegion_Path1);
                    bool Is_ModelRegion2 = File.Exists(productList.Product_list[Now_Product_ID].ModelRegion_Path2);
                    if (Is_Model1 == true && Is_Model2 == true)
                    {
                        try
                        {
                            HTuple scale = 4;
                            HTuple Row = 0;
                            HTuple Column = 0;
                            HTuple Angle = 0;
                            Measure measure = new Measure(manualImage_width, manualImage_Height);
                            HOperatorSet.ReadShapeModel(productList.Product_list[Now_Product_ID].StandraModel_Path1, out HTuple ModelID1);
                            HOperatorSet.ReadShapeModel(productList.Product_list[Now_Product_ID].StandraModel_Path2, out HTuple ModelID2);
                            if (Is_ModelRegion1 && Is_ModelRegion2)
                            {
                                HOperatorSet.ReadRegion(out HObject modelRegion1, productList.Product_list[Now_Product_ID].ModelRegion_Path1);
                                HOperatorSet.AreaCenter(modelRegion1, out HTuple area1, out HTuple row1, out HTuple column1);
                                HOperatorSet.HomMat2dIdentity(out HTuple homMat2D1);
                                HOperatorSet.HomMat2dScale(homMat2D1, scale, scale, row1, column1, out HTuple homMat2dScale1);
                                HOperatorSet.AffineTransRegion(modelRegion1, out HObject regionAffineTrans1, homMat2dScale1, "nearest_neighbor");
                                HOperatorSet.ReduceDomain(Images, regionAffineTrans1, out HObject image1);

                                HOperatorSet.ReadRegion(out HObject modelRegion2, productList.Product_list[Now_Product_ID].ModelRegion_Path2);
                                HOperatorSet.AreaCenter(modelRegion2, out HTuple area2, out HTuple row2, out HTuple column2);
                                HOperatorSet.HomMat2dIdentity(out HTuple homMat2D2);
                                HOperatorSet.HomMat2dScale(homMat2D2, scale, scale, row2, column2, out HTuple homMat2dScale2);
                                HOperatorSet.AffineTransRegion(modelRegion2, out HObject regionAffineTrans2, homMat2dScale2, "nearest_neighbor");
                                HOperatorSet.ReduceDomain(Images, regionAffineTrans2, out HObject image2);

                                //HOperatorSet.DispObj(regionAffineTrans1, hSmartWindowControl1.HalconWindow);
                                //HOperatorSet.DispObj(regionAffineTrans2, hSmartWindowControl1.HalconWindow);

                                Algorithm.Create_Stanrad_Point(image1, image2, out HObject RegionLine, out HObject Circle_Region, ModelID1, ModelID2, out Row, out Column, out Angle);

                            }
                            else
                                Algorithm.Create_Stanrad_Point(Images, out HObject RegionLine, out HObject Circle_Region, ModelID1, ModelID2, out Row, out Column, out Angle);

                            double Rotation_Center = Angle.D - productList.Product_list[Now_Product_ID].Standard_Angle;
                            if (Rotation_Center > 3) Rotation_Center = Rotation_Center - Math.PI;
                            if (Rotation_Center < -3) Rotation_Center = Rotation_Center + Math.PI;

                            HOperatorSet.VectorAngleToRigid(productList.Product_list[Now_Product_ID].Standard_Row, productList.Product_list[Now_Product_ID].Standard_Column, 0, Row, Column, Rotation_Center, out HTuple HomMat2DTranslate);
                            //获取所有区域结果
                            List<LineAndRecangelResult> lineAndRecangelResults = new List<LineAndRecangelResult>();
                            string path = "";
                            for (int i = 0; i < productList.Product_list[Now_Product_ID].FeaturesList.Count; i++)
                            {
                                path = productList.Product_list[Now_Product_ID].FeaturesList[i].Region_Path;
                                if (File.Exists(path))
                                {
                                    measure.GetResult(hSmartWindowControl1, productList.Product_list[Now_Product_ID].FeaturesList[i], Images, HomMat2DTranslate, path, lineAndRecangelResults);
                                }
                            }
                            //计算轴线
                            Feature feature1 = productList.Product_list[Now_Product_ID].FeaturesList.Find(x => x.Name.Contains("基准轴") && x.Name.Contains(","));
                            Feature feature2 = productList.Product_list[Now_Product_ID].FeaturesList.Find(x => x.Name.Contains("基准轴") && !x.Name.Contains(","));
                            //基准轴线
                            if (feature1!=null&& feature2!=null)
                            {
                                string pointName1 = feature1.Name.Split('_')[1].Split(',')[0];
                                string pointName2 = feature1.Name.Split('_')[1].Split(',')[1];
                                double startRow1 = lineAndRecangelResults.Find(x => x.name == pointName1).centerRow;
                                double startCol1 = lineAndRecangelResults.Find(x => x.name == pointName1).centerCol;
                                double endRow1 = lineAndRecangelResults.Find(x => x.name == pointName2).centerRow;
                                double endCol1 = lineAndRecangelResults.Find(x => x.name == pointName2).centerCol;
                                lineAndRecangelResults.Add(new LineAndRecangelResult() { name = feature1.Name, startRow = startRow1, startCol = startCol1, endRow = endRow1, endCol = endCol1 });
                                HOperatorSet.GenRegionLine(out HObject regionline1, startRow1, startCol1, endRow1, endCol1);
                                //投影轴线
                                string pointName3 = feature2.Name.Split('_')[1];
                                double startRow3 = lineAndRecangelResults.Find(x => x.name == pointName3).centerRow;
                                double startCol3 = lineAndRecangelResults.Find(x => x.name == pointName3).centerCol;
                                HOperatorSet.ProjectionPl(startRow3, startCol3, startRow1, startCol1, endRow1, endCol1, out HTuple rowProj, out HTuple colProj);
                                HOperatorSet.GenRegionLine(out HObject regionline2, startRow3, startCol3, rowProj, colProj);
                                lineAndRecangelResults.Add(new LineAndRecangelResult() { name = feature2.Name, startRow = startRow3, startCol = startCol3, endRow = rowProj, endCol = colProj });
                            }
                            //计算点构线
                            Feature feature3 = productList.Product_list[Now_Product_ID].FeaturesList.Find(x => x.Name.Contains("点构线") && x.Name.Contains(","));
                            if (feature3 != null)
                            {
                                //点构线
                                string pointName4 = feature3.Name.Split('_')[1].Split(',')[0];
                                string pointName5 = feature3.Name.Split('_')[1].Split(',')[1];
                                double startRow = lineAndRecangelResults.Find(x => x.name == pointName4).centerRow;
                                double startCol = lineAndRecangelResults.Find(x => x.name == pointName4).centerCol;
                                double endRow = lineAndRecangelResults.Find(x => x.name == pointName5).centerRow;
                                double endCol = lineAndRecangelResults.Find(x => x.name == pointName5).centerCol;
                                lineAndRecangelResults.Add(new LineAndRecangelResult() { name = feature3.Name, startRow = startRow, startCol = startCol, endRow = endRow, endCol = endCol });
                                HOperatorSet.GenRegionLine(out HObject regionline, startRow, startCol, endRow, endCol);
                            }
                            //测距
                            if (productList.Product_list[Now_Product_ID].MeasureList.Count > 0)
                            {

                                //Parallel.For(0, productList.Product_list[Now_Product_ID].MeasureList.Count, i => LeftStationMeasureResult.Add(productList.Product_list[Now_Product_ID].MeasureList[i].Measure_Tool_Run(hSmartWindowControl1, Images, manualImage_width, manualImage_Height, HomMat2DTranslate, Calibration_CameraLeft, ref temp_code, configfil.Left_Scaled)));
                                for (int i = 0; i < productList.Product_list[Now_Product_ID].MeasureList.Count; i++)
                                {
                                    LeftStationMeasureResult.Add(productList.Product_list[Now_Product_ID].MeasureList[i].Measure_Tool_Run(hSmartWindowControl1, Images, manualImage_width, manualImage_Height, HomMat2DTranslate, Calibration_CameraLeft, ref temp_code, configfil.Left_Scaled, lineAndRecangelResults, "Left"));

                                }
                                if (checkBox6.Checked == false)
                                {
                                    //二维码OK
                                    if (temp_code != "")
                                    {
                                        LeftStationCode = temp_code;
                                        PLC.Write("R2520", new string(' ', 80));
                                        PLC.Write("R2520", LeftStationCode);
                                        PLC.Write(configfil.TestCodeReading_Left, 1);
                                    }
                                    else //二维码NG
                                    {
                                        LeftStationCode = "Left" + ImageNumber.ToString();
                                        PLC.Write("R2520", new string(' ', 80));
                                        PLC.Write(configfil.TestCodeReading_Left, 2);
                                    }
                                    //移除名称为空的项
                                    //List<Measure_Result> list = LeftStationMeasureResult.FindAll(x => x.Measure_Name == "");
                                    //for (int i = 0; i < list.Count; i++)
                                    //{
                                    //    LeftStationMeasureResult.Remove(list[i]);
                                    //}

                                    //测量NG
                                    if (LeftStationMeasureResult.Where(a => a.Measure_Name != "" && a.Judge == false).Count() > 0)
                                    {
                                        OnFrameReadyFuncLNG(false);
                                    }
                                    else //测量OK
                                    {
                                        PLC.Write(configfil.TestMeasurement_Left, 1);
                                        PLC.Write(configfil.TestReult_Left, 1);
                                        DisplayTxt(richTextBox1, "左回复PLC  OK");
                                        HOperatorSet.SetFont(hSmartWindowControl1.HalconWindow, "default-Normal-30");
                                        HOperatorSet.DispText(hSmartWindowControl1.HalconWindow, "OK", "image", 20, 20, "green", "box", "false");
                                        SaveImageTestReult = "OK";
                                        CsvTestReult = "OK";
                                    }
                                }
                                else
                                {
                                    if (temp_code != "")
                                    {
                                        LeftStationCode = temp_code;
                                        PLC.Write("R2520", new string(' ', 80));
                                        PLC.Write("R2520", LeftStationCode);
                                    }
                                    PLC.Write(configfil.TestCodeReading_Left, 1);
                                    PLC.Write(configfil.TestMeasurement_Left, 1);
                                    PLC.Write(configfil.TestReult_Left, 1);
                                    DisplayTxt(richTextBox1, "左回复PLC  OK");
                                    HOperatorSet.SetFont(hSmartWindowControl1.HalconWindow, "default-Normal-30");
                                    HOperatorSet.DispText(hSmartWindowControl1.HalconWindow, "OK", "image", 20, 20, "green", "box", "false");
                                    SaveImageTestReult = "OK";
                                    MesJudgeL = "PASS";
                                    if (LeftStationMeasureResult.Where(a => a.Measure_Name != "" && a.Judge == false).Count() > 0)
                                    {
                                        CsvTestReult = "NG";
                                    }
                                }
                            }
                            else
                            {
                                HOperatorSet.SetFont(hSmartWindowControl1.HalconWindow, "default-Normal-30");
                                HOperatorSet.DispText(hSmartWindowControl1.HalconWindow, "没有测量工具", "window", 500, 500, "green", "box", "true");
                                OnFrameReadyFuncLNG();
                            }
                        }
                        catch (Exception ex)
                        {
                            OnFrameReadyFuncLNG();
                        }
                        if (LeftStationMeasureResult.Count > 0)
                        {
                            Debug.WriteLine("l result" + productList.Product_list[Now_Product_ID].MeasureList.Count);
                            this.Invoke(new Action(() =>
                            {
                                try
                                {
                                    dataGridView1.Rows.Clear();
                                    int count = dataGridView1.Rows.Count;
                                    for (int i = 0; i < LeftStationMeasureResult.Count; i++)
                                    {
                                        if (productList.Product_list[Now_Product_ID].MeasureList[i].Name=="")
                                            continue;
                                        dataGridView1.Rows.Add(new DataGridViewRow());
                                        count = dataGridView1.Rows.Count;
                                        dataGridView1.Rows[count-1].Cells[0].Value = count - 1;//序号
                                       
                                        dataGridView1.Rows[count-1].Cells[1].Value = productList.Product_list[Now_Product_ID].MeasureList[i].Name;//测量名称
                                        if (dataGridView1.Rows[count-1].Cells[1].Value.ToString() != "")
                                        {
                                            //测量值
                                            if (productList.Product_list[Now_Product_ID].MeasureList[i].Name.Contains("读码"))
                                                dataGridView1.Rows[count-1].Cells[2].Value = LeftStationCode;
                                            else if (productList.Product_list[Now_Product_ID].MeasureList[i].Name.Contains("椭圆测量"))
                                            {
                                                dataGridView1.Rows[count-1].Cells[2].Value = "长：" + LeftStationMeasureResult[i].Distance.ToString("f2") + "  直径：" + LeftStationMeasureResult[i].Width.ToString("f2");
                                            }
                                            else
                                                dataGridView1.Rows[count-1].Cells[2].Value = LeftStationMeasureResult[i].Distance.ToString("f2");
                                            //NG行的背景颜色设置为红色
                                            if (LeftStationMeasureResult[i].Judge == false)
                                            {
                                                dataGridView1.Rows[count-1].DefaultCellStyle.BackColor = Color.Red;
                                            }

                                            if (productList.Product_list[Now_Product_ID].MeasureList[i].Name.Contains("椭圆测量"))
                                            {
                                                dataGridView1.Rows[count-1].Cells[3].Value = "长：" + productList.Product_list[Now_Product_ID].MeasureList[i].EllipseSetValueL + "  直径：" + productList.Product_list[Now_Product_ID].MeasureList[i].EllipseSetValueW;
                                                //值下限
                                                dataGridView1.Rows[count-1].Cells[4].Value = "长：" + productList.Product_list[Now_Product_ID].MeasureList[i].EllipseMaxValueL + "  直径：" + productList.Product_list[Now_Product_ID].MeasureList[i].EllipseMaxValueW;
                                                //值上限
                                                dataGridView1.Rows[count-1].Cells[5].Value = "长：" + productList.Product_list[Now_Product_ID].MeasureList[i].EllipseMinValueL + "  直径：" + productList.Product_list[Now_Product_ID].MeasureList[i].EllipseMinValueW;
                                            }
                                            else
                                            {
                                                //设定值
                                                dataGridView1.Rows[count-1].Cells[3].Value = productList.Product_list[Now_Product_ID].MeasureList[i].SetValue;
                                                //值下限
                                                dataGridView1.Rows[count-1].Cells[4].Value = productList.Product_list[Now_Product_ID].MeasureList[i].MinValue;

                                                //值上限
                                                dataGridView1.Rows[count-1].Cells[5].Value = productList.Product_list[Now_Product_ID].MeasureList[i].MaxValue;
                                            }

                                        }
                                       
                                    }
                                }
                                catch (Exception ex)
                                {


                                }

                            }));

                            Debug.WriteLine("l grid" + dataGridView1.Rows.Count);
                        }
                    }
                    else
                    {
                        OnFrameReadyFuncLNG();
                    }
                }
                else
                    OnFrameReadyFuncLNG();
                

                if (Measure_record == true)
                {
                    //if (Directory.Exists(Directory.GetCurrentDirectory() + "//record") == false) Directory.CreateDirectory(Directory.GetCurrentDirectory() + "//record");
                    //FileStream fileStream = new FileStream(Directory.GetCurrentDirectory() + "//record//Left.csv", FileMode.Append, FileAccess.Write);
                    //StreamWriter streamWriter = new StreamWriter(fileStream, Encoding.UTF8);
                    //string Tilte = "";
                    //string Content = "";
                    //foreach (Measure_Result item in LeftStationMeasureResult)
                    //{
                    //    if (item.Measure_Name!="")
                    //    {
                    //        Tilte = Tilte + item.Measure_Name + ",";
                    //        Content = Content + item.Distance.ToString("0.00") + ",";
                    //    }

                    //}
                    //streamWriter.WriteLine(Tilte);
                    //streamWriter.WriteLine(Content);
                    //streamWriter.Close();
                    //fileStream.Close();
                    tool.WriteCsv(LeftStationMeasureResult, "Left", temp_code, CsvTestReult, productList.Product_list[Now_Product_ID].ProductName);
                }
                if (SaveImagecheck == true)
                {
                    Task task = Task.Run(() => SaveImages("IKCamera", Images, "LineScanLeft", SaveImageTestReult, LeftStationCode));
                }
                Task.Run(new Action(() =>
                {
                    int i = 0;
                    try
                    {
                        if (!productList.Product_list[Now_Product_ID].Pinchek)
                        {
                            tool.WriteMesTxt(configfil.MesSavePath, LeftStationCode, MesJudgeL, LeftStationMeasureResult,LeftPinStationMeasureResult,false);
                            if (SaveImageTestReult == "OK")
                            {
                                ProductTotal.OKAdd();
                            }
                            else
                            {
                                ProductTotal.NGAdd();
                            }
                        }
                        else
                        {
                            //Debug.WriteLine(DateTime.Now.ToString("开始等待" +"yyyy/MM/dd HH:mm:ss fff"));
                            while (i < 30)
                            {
                                if (isLeftPinStatus)
                                {
                                    tool.WriteMesTxt(configfil.MesSavePath, LeftStationCode, MesJudgeL, LeftStationMeasureResult, LeftPinStationMeasureResult, true);
                                    if (SaveImageTestReult == "OK" && SaveImageTestReultPIN == "OK")
                                    {
                                        ProductTotal.OKAdd();
                                    }
                                    else
                                    {
                                        ProductTotal.NGAdd();
                                    }
                                    isLeftPinStatus = false;
                                    Debug.WriteLine(i);
                                    break;
                                }
                                Thread.Sleep(100);
                                i++;
                            }
                            //Debug.WriteLine(DateTime.Now.ToString("结束等待"+ "yyyy/MM/dd HH:mm:ss fff"));
                        }

                    }
                    catch (Exception ex)
                    {
                        DisplayTxt(richTextBox1, "写入MES文件失败，请检查MES文件保存路径");

                    }
                    ProductTotal.Yield();
                    this.BeginInvoke((Action<Label>)(theLable => { theLable.Text = ProductTotal.ProductCount.ToString(); }), label136);
                    this.BeginInvoke((Action<Label>)(theLable => { theLable.Text = ProductTotal.ProductNGCount.ToString(); }), label138);
                    this.BeginInvoke((Action<Label>)(theLable => { theLable.Text = ProductTotal.Yield(); }), label140);

                }));
                //this.Invoke(new Action(() =>
                //{
                //    try
                //    {
                //        tool.WriteMesTxt(configfil.MesSavePath, LeftStationCode, MesJudgeL, LeftStationMeasureResult);
                //    }
                //    catch (Exception ex)
                //    {

                //        DisplayTxt(richTextBox1, "写入MES文件失败，请检查MES文件保存路径");
                //    }

                //}));
            }
            else
                OnFrameReadyFuncLNG();
            ImageNumber++;
            camera.m_nCurFrameIndexL++;
            camera.m_nCurFrameIndexL = camera.m_nCurFrameIndexL % camera.m_nTotalFrameCountL;
            //************************************************************************************************************
           

        }
        public void OnFrameReadyFuncLNG(bool isClearCode = true )
        {
            if (isClearCode)
            {
                PLC.Write("R2520", new string(' ', 80));
                PLC.Write(configfil.TestCodeReading_Left, 2);
            }
            MesJudgeL = "NG";
            PLC.Write(configfil.TestMeasurement_Left, 2);
            PLC.Write(configfil.TestReult_Left, 2);
            DisplayTxt(richTextBox1, "左回复PLC  NG");
            HOperatorSet.SetFont(hSmartWindowControl1.HalconWindow, "default-Normal-30");
            HOperatorSet.DispText(hSmartWindowControl1.HalconWindow, "NG", "image", 20, 20, "red", "box", "false");
            SaveImageTestReult = "NG";
            CsvTestReult = "NG";

        }
        public void OnFrameReadyFuncR(IntPtr pParam)
        {
            DisplayTxt(richTextBox1, "右接收到触发信号");
            Console.WriteLine("Grab frame ready");
            IntPtr hDev = (IntPtr)pParam;
            IntPtr pUserBuffer = IntPtr.Zero;
            int nFrameSize = 0;
            int nFrameCount = 0;
            int width = 0, height = 0, nDepth = 0, nChannels = 0, nImageType = 0;
            IKapBoard.IKAPBUFFERSTATUS status = new IKapBoard.IKAPBUFFERSTATUS();
            try
            {
                IKapBoard.IKapGetInfo(hDev, (uint)INFO_ID.IKP_FRAME_COUNT, ref nFrameCount);
                IKapBoard.IKapGetBufferStatus(hDev, camera.m_nCurFrameIndexR, ref status);
            }
            catch (Exception ex)
            {

                DisplayTxt(richTextBox1, "右 IKapBoard 错误：" + ex);
            }


            // 当图像缓冲区满时。
            //
            // When the buffer is full.
            if (status.uFull == 1)
            {
                // 获取一帧图像的大小。
                //
                // Get the size of a frame of image.
                IKapBoard.IKapGetInfo(hDev, (uint)INFO_ID.IKP_FRAME_SIZE, ref nFrameSize);
                IKapBoard.IKapGetInfo(camera.m_hBoardR, (uint)INFO_ID.IKP_IMAGE_WIDTH, ref width);
                IKapBoard.IKapGetInfo(camera.m_hBoardR, (uint)INFO_ID.IKP_IMAGE_HEIGHT, ref height);
                IKapBoard.IKapGetInfo(camera.m_hBoardR, (uint)INFO_ID.IKP_DATA_FORMAT, ref nDepth);
                IKapBoard.IKapGetInfo(camera.m_hBoardR, (uint)INFO_ID.IKP_IMAGE_TYPE, ref nImageType);
                switch (nImageType)
                {
                    case 0:
                        nChannels = 1;
                        break;
                    case 1:
                    case 3:
                        nChannels = 3;
                        break;
                    case 2:
                    case 4:
                        nChannels = 4;
                        break;
                }

                // 获取缓冲区地址。
                //
                // Get the buffer address.
                IKapBoard.IKapGetBufferAddress(hDev, camera.m_nCurFrameIndexR, ref pUserBuffer);
                //图像转换

                List<Bitmap> Imagelist = new List<Bitmap>();
                DisplayTxt(richTextBox1, "右获取一张图像");
                HOperatorSet.GenImage1Extern(out HObject Images, "byte", width, height, pUserBuffer, IntPtr.Zero);
               
                RightStationMeasureResult.Clear();
                string temp_code = "";
                MesJudgeR = "PASS";
                CsvTestReult = "OK";
                HOperatorSet.GetImageSize(Images, out manualImage_width, out manualImage_Height);
                HOperatorSet.SetPart(hSmartWindowControl2.HalconWindow, 0, 0, manualImage_Height - 1, manualImage_width - 1);
                HOperatorSet.DispObj(Images, hSmartWindowControl2.HalconWindow);
                hSmartWindowControl2.SetFullImagePart();
                HOperatorSet.SetFont(hSmartWindowControl2.HalconWindow, "default-Normal-12");
                if (File.Exists(productList.Product_list[Now_Product_ID].StandraModel_Path1) == true)
                {
                    bool Is_Model1 = File.Exists(productList.Product_list[Now_Product_ID].StandraModel_Path1);
                    bool Is_Model2 = File.Exists(productList.Product_list[Now_Product_ID].StandraModel_Path2);
                    bool Is_ModelRegion1 = File.Exists(productList.Product_list[Now_Product_ID].ModelRegion_Path1);
                    bool Is_ModelRegion2 = File.Exists(productList.Product_list[Now_Product_ID].ModelRegion_Path2);
                    if (Is_Model1 == true && Is_Model2 == true)
                    {

                        try
                        {

                            HTuple scale = 4;
                            HTuple Row = 0;
                            HTuple Column = 0;
                            HTuple Angle = 0;
                            Measure measure = new Measure(manualImage_width, manualImage_Height);
                            HOperatorSet.ReadShapeModel(productList.Product_list[Now_Product_ID].StandraModel_Path1, out HTuple ModelID1);
                            HOperatorSet.ReadShapeModel(productList.Product_list[Now_Product_ID].StandraModel_Path2, out HTuple ModelID2);
                            if (Is_ModelRegion1 && Is_ModelRegion2)
                            {
                                HOperatorSet.ReadRegion(out HObject modelRegion1, productList.Product_list[Now_Product_ID].ModelRegion_Path1);
                                HOperatorSet.AreaCenter(modelRegion1, out HTuple area1, out HTuple row1, out HTuple column1);
                                HOperatorSet.HomMat2dIdentity(out HTuple homMat2D1);
                                HOperatorSet.HomMat2dScale(homMat2D1, scale, scale, row1, column1, out HTuple homMat2dScale1);
                                HOperatorSet.AffineTransRegion(modelRegion1, out HObject regionAffineTrans1, homMat2dScale1, "nearest_neighbor");
                                HOperatorSet.ReduceDomain(Images, regionAffineTrans1, out HObject image1);

                                HOperatorSet.ReadRegion(out HObject modelRegion2, productList.Product_list[Now_Product_ID].ModelRegion_Path2);
                                HOperatorSet.AreaCenter(modelRegion2, out HTuple area2, out HTuple row2, out HTuple column2);
                                HOperatorSet.HomMat2dIdentity(out HTuple homMat2D2);
                                HOperatorSet.HomMat2dScale(homMat2D2, scale, scale, row2, column2, out HTuple homMat2dScale2);
                                HOperatorSet.AffineTransRegion(modelRegion2, out HObject regionAffineTrans2, homMat2dScale2, "nearest_neighbor");
                                HOperatorSet.ReduceDomain(Images, regionAffineTrans2, out HObject image2);

                                //HOperatorSet.DispObj(regionAffineTrans1, hSmartWindowControl1.HalconWindow);
                                //HOperatorSet.DispObj(regionAffineTrans2, hSmartWindowControl1.HalconWindow);

                                Algorithm.Create_Stanrad_Point(image1, image2, out HObject RegionLine, out HObject Circle_Region, ModelID1, ModelID2, out Row, out Column, out Angle);

                            }
                            else
                                Algorithm.Create_Stanrad_Point(Images, out HObject RegionLine, out HObject Circle_Region, ModelID1, ModelID2, out Row, out Column, out Angle);
                            double Rotation_Center = Angle.D - productList.Product_list[Now_Product_ID].Standard_Angle;
                            if (Rotation_Center > 3) Rotation_Center = Rotation_Center - Math.PI;
                            if (Rotation_Center < -3) Rotation_Center = Rotation_Center + Math.PI;
                            HOperatorSet.VectorAngleToRigid(productList.Product_list[Now_Product_ID].Standard_Row, productList.Product_list[Now_Product_ID].Standard_Column, 0, Row, Column, Rotation_Center, out HTuple HomMat2DTranslate);

                            if (productList.Product_list[Now_Product_ID].MeasureList.Count > 0)
                            {
                                //获取所有区域结果
                                List<LineAndRecangelResult> lineAndRecangelResults = new List<LineAndRecangelResult>();
                                string path = "";
                                for (int i = 0; i < productList.Product_list[Now_Product_ID].FeaturesList.Count; i++)
                                {
                                    path = productList.Product_list[Now_Product_ID].FeaturesList[i].Region_Path;
                                    if (File.Exists(path))
                                    {
                                        measure.GetResult(hSmartWindowControl2, productList.Product_list[Now_Product_ID].FeaturesList[i], Images, HomMat2DTranslate, path, lineAndRecangelResults);
                                    }
                                }
                                //计算轴线
                                Feature feature1 = productList.Product_list[Now_Product_ID].FeaturesList.Find(x => x.Name.Contains("基准轴") && x.Name.Contains(","));
                                Feature feature2 = productList.Product_list[Now_Product_ID].FeaturesList.Find(x => x.Name.Contains("基准轴") && !x.Name.Contains(","));
                                //基准轴线
                                if (feature1 != null && feature2 != null)
                                {
                                    string pointName1 = feature1.Name.Split('_')[1].Split(',')[0];
                                    string pointName2 = feature1.Name.Split('_')[1].Split(',')[1];
                                    double startRow1 = lineAndRecangelResults.Find(x => x.name == pointName1).centerRow;
                                    double startCol1 = lineAndRecangelResults.Find(x => x.name == pointName1).centerCol;
                                    double endRow1 = lineAndRecangelResults.Find(x => x.name == pointName2).centerRow;
                                    double endCol1 = lineAndRecangelResults.Find(x => x.name == pointName2).centerCol;
                                    lineAndRecangelResults.Add(new LineAndRecangelResult() { name = feature1.Name, startRow = startRow1, startCol = startCol1, endRow = endRow1, endCol = endCol1 });
                                    HOperatorSet.GenRegionLine(out HObject regionline1, startRow1, startCol1, endRow1, endCol1);
                                    //投影轴线
                                    string pointName3 = feature2.Name.Split('_')[1];
                                    double startRow3 = lineAndRecangelResults.Find(x => x.name == pointName3).centerRow;
                                    double startCol3 = lineAndRecangelResults.Find(x => x.name == pointName3).centerCol;
                                    HOperatorSet.ProjectionPl(startRow3, startCol3, startRow1, startCol1, endRow1, endCol1, out HTuple rowProj, out HTuple colProj);
                                    HOperatorSet.GenRegionLine(out HObject regionline2, startRow3, startCol3, rowProj, colProj);
                                    lineAndRecangelResults.Add(new LineAndRecangelResult() { name = feature2.Name, startRow = startRow3, startCol = startCol3, endRow = rowProj, endCol = colProj });
                                }
                                //计算点构线
                                Feature feature3 = productList.Product_list[Now_Product_ID].FeaturesList.Find(x => x.Name.Contains("点构线") && x.Name.Contains(","));
                                if (feature3 != null)
                                {
                                    //点构线
                                    string pointName4 = feature3.Name.Split('_')[1].Split(',')[0];
                                    string pointName5 = feature3.Name.Split('_')[1].Split(',')[1];
                                    double startRow = lineAndRecangelResults.Find(x => x.name == pointName4).centerRow;
                                    double startCol = lineAndRecangelResults.Find(x => x.name == pointName4).centerCol;
                                    double endRow = lineAndRecangelResults.Find(x => x.name == pointName5).centerRow;
                                    double endCol = lineAndRecangelResults.Find(x => x.name == pointName5).centerCol;
                                    lineAndRecangelResults.Add(new LineAndRecangelResult() { name = feature3.Name, startRow = startRow, startCol = startCol, endRow = endRow, endCol = endCol });
                                    HOperatorSet.GenRegionLine(out HObject regionline, startRow, startCol, endRow, endCol);
                                }
                                //测距
                                //Parallel.For(0, productList.Product_list[Now_Product_ID].MeasureList.Count, i => RightStationMeasureResult.Add(productList.Product_list[Now_Product_ID].MeasureList[i].Measure_Tool_Run(hSmartWindowControl2, Images, manualImage_width, manualImage_Height, HomMat2DTranslate, Calibration_CameraRight, ref temp_code, configfil.Right_Scaled)));
                                for (int i = 0; i < productList.Product_list[Now_Product_ID].MeasureList.Count; i++)
                                {
                                    RightStationMeasureResult.Add(productList.Product_list[Now_Product_ID].MeasureList[i].Measure_Tool_Run(hSmartWindowControl2, Images, manualImage_width, manualImage_Height, HomMat2DTranslate, Calibration_CameraRight, ref temp_code, configfil.Right_Scaled, lineAndRecangelResults, "Right"));

                                }
                                if (checkBox6.Checked == false)
                                {
                                    //二维码OK
                                    if (temp_code != "")
                                    {
                                        RightStationCode = temp_code;
                                        PLC.Write("R2820", new string(' ', 80));
                                        PLC.Write("R2820", RightStationCode);
                                        PLC.Write(configfil.TestCodeReading_Right, 1);
                                    }
                                    else //二维码NG
                                    {
                                        RightStationCode = "Right" + ImageNumber.ToString();
                                        PLC.Write("R2820", new string(' ', 80));
                                        PLC.Write(configfil.TestCodeReading_Right, 2);
                                    }
                                    //移除名称为空的项
                                    //List<Measure_Result> list = RightStationMeasureResult.FindAll(x => x.Measure_Name == "");
                                    //for (int i = 0; i < list.Count; i++)
                                    //{
                                    //    RightStationMeasureResult.Remove(list[i]);
                                    //}
                                    //测量NG
                                    if (RightStationMeasureResult.Where(a => a.Measure_Name != "" && a.Judge == false).Count() > 0)
                                    {

                                        OnFrameReadyFuncRNG(false);
                                    }
                                    else //测量OK
                                    {
                                        PLC.Write(configfil.TestMeasurement_Right, 1);
                                        PLC.Write(configfil.TestReult_Right, 1);
                                        DisplayTxt(richTextBox1, "右回复PLC  OK");
                                        HOperatorSet.SetFont(hSmartWindowControl2.HalconWindow, "default-Normal-30");
                                        HOperatorSet.DispText(hSmartWindowControl2.HalconWindow, "OK", "image", 20, 20, "green", "box", "false");
                                        SaveImageTestReult = "OK";
                                        CsvTestReult = "OK";
                                    }
                                }
                                else
                                {
                                    if (temp_code != "")
                                    {
                                        RightStationCode = temp_code;
                                        PLC.Write("R2820", new string(' ', 80));
                                        PLC.Write("R2820", RightStationCode);
                                    }
                                    PLC.Write(configfil.TestCodeReading_Right, 1);
                                    PLC.Write(configfil.TestMeasurement_Right, 1);
                                    PLC.Write(configfil.TestReult_Right, 1);
                                    DisplayTxt(richTextBox1, "右回复PLC  OK");
                                    HOperatorSet.SetFont(hSmartWindowControl2.HalconWindow, "default-Normal-30");
                                    HOperatorSet.DispText(hSmartWindowControl2.HalconWindow, "OK", "image", 20, 20, "green", "box", "false");
                                    SaveImageTestReult = "OK";
                                    MesJudgeR = "PASS";
                                    if (RightStationMeasureResult.Where(a => a.Measure_Name != "" && a.Judge == false).Count() > 0)
                                    {
                                        CsvTestReult = "NG";
                                    }
                                }
                            }
                            else
                            {
                                HOperatorSet.SetFont(hSmartWindowControl2.HalconWindow, "default-Normal-30");
                                HOperatorSet.DispText(hSmartWindowControl2.HalconWindow, "没有测量工具", "window", 500, 500, "green", "box", "true");
                                OnFrameReadyFuncRNG();
                            }
                        }
                        catch (Exception ex)
                        {
                            OnFrameReadyFuncRNG();

                        }
                        if (RightStationMeasureResult.Count > 0)
                        {
                            Debug.WriteLine("r result" + RightStationMeasureResult.Count);
                            this.Invoke(new Action(() =>
                            {

                                try
                                {
                                    dataGridView2.Rows.Clear();
                                    int count = dataGridView2.Rows.Count;
                                    for (int i = 0; i < RightStationMeasureResult.Count; i++)
                                    {
                                        if (productList.Product_list[Now_Product_ID].MeasureList[i].Name == "")
                                            continue;
                                        dataGridView2.Rows.Add(new DataGridViewRow());
                                        count = dataGridView2.Rows.Count;
                                        dataGridView2.Rows[count-1].Cells[0].Value = count-1;//序号
                                        dataGridView2.Rows[count-1].Cells[1].Value = productList.Product_list[Now_Product_ID].MeasureList[i].Name;//测量名称
                                        if (dataGridView2.Rows[count-1].Cells[1].Value.ToString() != "")
                                        {
                                            if (productList.Product_list[Now_Product_ID].MeasureList[i].Name.Contains("读码"))
                                            {
                                                dataGridView2.Rows[count-1].Cells[2].Value = RightStationCode;
                                            }
                                            else if (productList.Product_list[Now_Product_ID].MeasureList[i].Name.Contains("椭圆测量"))
                                            {
                                                dataGridView2.Rows[count-1].Cells[2].Value = "长：" + RightStationMeasureResult[i].Distance.ToString("f2") + "  直径：" + RightStationMeasureResult[i].Width.ToString("f2");
                                            }
                                            else
                                                dataGridView2.Rows[count-1].Cells[2].Value = RightStationMeasureResult[i].Distance.ToString("f2");
                                            //NG行的背景颜色设置为红色
                                            if (RightStationMeasureResult[i].Judge == false)
                                            {
                                                dataGridView2.Rows[count-1].DefaultCellStyle.BackColor = Color.Red;
                                            }
                                            if (productList.Product_list[Now_Product_ID].MeasureList[i].Name.Contains("椭圆测量"))
                                            {
                                                dataGridView2.Rows[count - 1].Cells[3].Value = "长：" + productList.Product_list[Now_Product_ID].MeasureList[i].EllipseSetValueL + "  直径：" + productList.Product_list[Now_Product_ID].MeasureList[i].EllipseSetValueW;
                                                //值下限
                                                dataGridView2.Rows[count - 1].Cells[4].Value = "长：" + productList.Product_list[Now_Product_ID].MeasureList[i].EllipseMaxValueL + "  直径：" + productList.Product_list[Now_Product_ID].MeasureList[i].EllipseMaxValueW;
                                                //值上限
                                                dataGridView2.Rows[count - 1].Cells[5].Value = "长：" + productList.Product_list[Now_Product_ID].MeasureList[i].EllipseMinValueL + "  直径：" + productList.Product_list[Now_Product_ID].MeasureList[i].EllipseMinValueW;
                                            }
                                            else
                                            {
                                                //设定值
                                                dataGridView2.Rows[count-1].Cells[3].Value = productList.Product_list[Now_Product_ID].MeasureList[i].SetValue;
                                                //值下限
                                                dataGridView2.Rows[count-1].Cells[4].Value = productList.Product_list[Now_Product_ID].MeasureList[i].MinValue;
                                                //值上限
                                                dataGridView2.Rows[count-1].Cells[5].Value = productList.Product_list[Now_Product_ID].MeasureList[i].MaxValue;
                                            }
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {


                                }
                            }));
                            Debug.WriteLine("r grid" + dataGridView2.Rows.Count);
                        }

                    }
                    else
                    {
                        OnFrameReadyFuncRNG();
                    }
                }
                else
                    OnFrameReadyFuncRNG();

                if (Measure_record == true)
                {
                    //if (Directory.Exists(Directory.GetCurrentDirectory() + "//record") == false) Directory.CreateDirectory(Directory.GetCurrentDirectory() + "//record");
                    //FileStream fileStream = new FileStream(Directory.GetCurrentDirectory() + "//record//Right.csv", FileMode.Append, FileAccess.Write);
                    //StreamWriter streamWriter = new StreamWriter(fileStream, Encoding.UTF8);
                    //string Tilte = "";
                    //string Content = "";
                    //foreach (Measure_Result item in RightStationMeasureResult)
                    //{
                    //    if (item.Measure_Name!="")
                    //    {
                    //        Tilte = Tilte + item.Measure_Name + ",";
                    //        Content = Content + item.Distance.ToString("0.00") + ",";
                    //    }

                    //}
                    //streamWriter.WriteLine(Tilte);
                    //streamWriter.WriteLine(Content);
                    //streamWriter.Close();
                    //fileStream.Close();
                    tool.WriteCsv(RightStationMeasureResult, "Right", temp_code, CsvTestReult, productList.Product_list[Now_Product_ID].ProductName);
                }
                if (SaveImagecheck == true)
                {
                    Task task = Task.Run(() => SaveImages("IKCamera", Images, "LineScanRight", SaveImageTestReult, RightStationCode));
                }
                Task.Run(new Action(() =>
                {
                    int i = 0;
                    try
                    {
                        if (!productList.Product_list[Now_Product_ID].Pinchek)
                        {
                            tool.WriteMesTxt(configfil.MesSavePath, RightStationCode, MesJudgeR, RightStationMeasureResult,RightPinStationMeasureResult, false);
                            if (SaveImageTestReult == "OK")
                            {
                                ProductTotal.OKAdd();
                            }
                            else
                            {
                                ProductTotal.NGAdd();
                            }
                        }
                        else
                        {
                            //Debug.WriteLine(DateTime.Now.ToString("开始等待" +"yyyy/MM/dd HH:mm:ss fff"));
                            while (i < 30)
                            {
                                if (isRightPinStatus)
                                {
                                    tool.WriteMesTxt(configfil.MesSavePath, RightStationCode, MesJudgeR, RightStationMeasureResult, RightPinStationMeasureResult, true);
                                    if (SaveImageTestReult == "OK" && SaveImageTestReultPIN == "OK")
                                    {
                                        ProductTotal.OKAdd();
                                    }
                                    else
                                    {
                                        ProductTotal.NGAdd();
                                    }
                                    isRightPinStatus = false;
                                    Debug.WriteLine(i);
                                    break;
                                }
                                Thread.Sleep(100);
                                i++;
                            }
                            //Debug.WriteLine(DateTime.Now.ToString("结束等待"+ "yyyy/MM/dd HH:mm:ss fff"));
                        }

                    }
                    catch (Exception ex)
                    {
                        DisplayTxt(richTextBox1, "写入MES文件失败，请检查MES文件保存路径");

                    }
                    ProductTotal.Yield();
                    this.BeginInvoke((Action<Label>)(theLable => { theLable.Text = ProductTotal.ProductCount.ToString(); }), label136);
                    this.BeginInvoke((Action<Label>)(theLable => { theLable.Text = ProductTotal.ProductNGCount.ToString(); }), label138);
                    this.BeginInvoke((Action<Label>)(theLable => { theLable.Text = ProductTotal.Yield(); }), label140);

                }));
                //this.Invoke(new Action(() =>
                //{
                //    try
                //    {
                //        //tool.WriteMesTxt(configfil.MesSavePath, RightStationCode, MesJudgeR, RightStationMeasureResult);
                //    }
                //    catch (Exception ex)
                //    {

                //        DisplayTxt(richTextBox1, "写入MES文件失败，请检查MES文件保存路径");
                //    }

                //}));
            }
            else
                OnFrameReadyFuncRNG();

            ImageNumber++;
            camera.m_nCurFrameIndexR++;
            camera.m_nCurFrameIndexR = camera.m_nCurFrameIndexR % camera.m_nTotalFrameCountR;
        }
        public void OnFrameReadyFuncRNG(bool isClearCode = true)
        {
            if (isClearCode)
            {
                PLC.Write("R2820", new string(' ', 80));
                PLC.Write(configfil.TestCodeReading_Right, 2);
            }
            MesJudgeR = "NG";
            PLC.Write(configfil.TestMeasurement_Right, 2);
            PLC.Write(configfil.TestReult_Right, 2);
            DisplayTxt(richTextBox1, "右回复PLC  NG");
            HOperatorSet.SetFont(hSmartWindowControl2.HalconWindow, "default-Normal-30");
            HOperatorSet.DispText(hSmartWindowControl2.HalconWindow, "NG", "image", 20, 20, "red", "box", "false");
            SaveImageTestReult = "NG";
            CsvTestReult = "NG";
        }
        public void btnStartGrab_Click(object sender, EventArgs e)
        {
            IKapBoard.IKapStartGrab(camera.m_hBoardL, Collection_method);
            IKapBoard.IKapStartGrab(camera.m_hBoardR, Collection_method);
            DisplayTxt(richTextBox1, "等待PLC触发拍照");

        }

        private void btnStopGrab_Click(object sender, EventArgs e)
        {
            IKapBoard.IKapStopGrab(camera.m_hBoardL);
            DisplayTxt(richTextBox1, "停止采集");
        }
        private void btnConfigureFrameGrabber_Click(object sender, EventArgs e)
        {
            Configurationfile = camera.ConfigureFrameGrabber(OnFrameReadyFuncL, true, configfil.CameraNames[IkCameraNum].SerialNumber, "Left");
            if (Configurationfile == true)
            {
                DisplayTxt(richTextBox1, "配置文件 " + configfil.LeftConfigurationfilepath + "  已打开");
            }
            else { DisplayTxt(richTextBox1, "配置文件 " + configfil.LeftConfigurationfilepath + "  打开异常"); }
            camera.SetFrameTrigger();
            ReadConfigfilState();
        }
        private void btnConnectCameras_Click(object sender, EventArgs e)
        {
            ConnectCameras(true);
        }
        #region 消息提示
        public void DisplayTxt(RichTextBox richText, string content)

        {
            string date = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
            if (richText.InvokeRequired == true)
            {
                this.BeginInvoke((Action<RichTextBox>)(text => { text.AppendText(date + ":" + content + "\n"); if (text.Text.Length > 10000) text.Clear(); text.HideSelection = false; }), richText);
            }
            else
            {
                richText.AppendText(date + ":" + content + "\n");
                richTextBox1.HideSelection = false;
                if (richText.Text.Length > 10000) richText.Clear();
            }

        }

        private void Form1_Resize(object sender, EventArgs e)
        {
            autoZone.ReWinformLayout(this.Width, this.Height, this);
        }
        #endregion

        private void btnChooseImagePath_Click(object sender, EventArgs e)
        {
            configfil.SaveImagePath = tool.OpenSaveImagePath();
            if (configfil.SaveImagePath != "")
            {
                DialogResult result = MessageBox.Show("是否将图片存储在路径下" + configfil.SaveImagePath, "提示", MessageBoxButtons.YesNoCancel);
                if (result == DialogResult.Yes)
                {
                    tool.SaveConfigFile(configfil);
                    MessageBox.Show("图片存储在路径已更新 " + configfil.SaveImagePath, "提示");
                    textBox3.Text = configfil.SaveImagePath;
                }
            }
        }

        private void ckbSaveImage_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked == true)
            {
                SaveImagecheck = true;
            }
            else
            {
                SaveImagecheck = false;
            }
        }
        /// <summary>
        /// 保存参数按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSaveConfig_Click(object sender, EventArgs e)
        {
            try
            {
                configfil.SaveImageCheck = SaveImagecheck;
                configfil.SaveImagePath = textBox3.Text;
                configfil.LeftConfigurationfilepath = textBox4.Text;
                configfil.HikLeftCameraSeria = textBox5.Text;
                configfil.HikRightCameraSeria = textBox23.Text;
                configfil.SerialNumberL = textBox24.Text;
                configfil.SerialNumberR = textBox25.Text;
                tool.SaveConfigFile(configfil);
                MessageBox.Show("保存成功");
            }
            catch (Exception ex)
            {
                MessageBox.Show("保存异常" + ex);
            }

        }

        private void CameraContinousImage(HikVisionCamera camera, HSmartWindowControl hSmartWindowControl)
        {
            Bitmap Hikgetimage = null;
            hSmartWindowControl.HalconWindow.ClearWindow();
            while (continuousImage)
            {
                Hikgetimage = camera.GetImageBitMap();
                ImageConvert.Bitmap2HObjectS(Hikgetimage, out HObject Hikgetimagewindow);
                HOperatorSet.GetImageSize(Hikgetimagewindow, out HTuple Hikgetimagewindow_width, out HTuple Hikgetimagewindow_Height);
                HOperatorSet.SetPart(hSmartWindowControl.HalconWindow, 0, 0, Hikgetimagewindow_Height - 1, Hikgetimagewindow_width - 1);
                HOperatorSet.DispObj(Hikgetimagewindow, hSmartWindowControl.HalconWindow);
                hSmartWindowControl.SetFullImagePart();
                Thread.Sleep(100);
                Hikgetimagewindow.Dispose();
                Hikgetimagewindow_width.Dispose();
                Hikgetimagewindow_Height.Dispose();
            }
        }

        private void button8_Click(object sender, EventArgs e)
        {
            List<Bitmap> Imagelist = new List<Bitmap>();
            Bitmap Hikbitmap = null;

            Hikbitmap = HikLeftCamera.GetImageBitMap();
            Imagelist.Add(Hikbitmap);

        }

        private void button7_Click(object sender, EventArgs e)
        {
            try
            {
                configfil.HikLeftCameraSeria = textBox5.Text;
                tool.SaveConfigFile(configfil);
            }
            catch (Exception ex)
            {
                MessageBox.Show("异常！" + ex);
            }

        }

        private void button11_Click(object sender, EventArgs e)
        {
            try
            {
                if (comboBox1.SelectedItem != null)
                {
                    if (comboBox1.SelectedItem.ToString() == "海康左" + configfil.HikLeftCameraSeria)
                    {
                        if (textBox1.Text != null)
                        {
                            configfil.HikLeftCameraExposureTime = Convert.ToInt32(textBox1.Text);
                            HikLeftCamera.m_MyCamera.SetFloatValue("ExposureTime", (int)configfil.HikLeftCameraExposureTime);
                        }
                    }
                    if (comboBox1.SelectedItem.ToString() == "海康右" + configfil.HikRightCameraSeria)
                    {
                        if (textBox1.Text != null)
                        {
                            configfil.HikRightCameraExposureTime = Convert.ToInt32(textBox1.Text);
                            HikRightCamera.m_MyCamera.SetFloatValue("ExposureTime", (int)configfil.HikRightCameraExposureTime);
                        }
                    }
                    tool.SaveConfigFile(configfil);
                }
                else { MessageBox.Show("请选择需要设置的相机"); }
            }
            catch (Exception ex)
            {
                MessageBox.Show("异常！" + ex);
            }

        }

        private void button9_Click(object sender, EventArgs e)
        {
            if (comboBox1.SelectedItem != null)
            {
                if (comboBox1.SelectedItem.ToString() == "海康左" + configfil.HikLeftCameraSeria)
                {

                    textBox1.Text = Convert.ToString(configfil.HikLeftCameraExposureTime);
                    if (GetImage_task_Hik == null)
                    {
                        continuousImage = true;
                        GetImage_task_Hik = Task.Run(() => CameraContinousImage(HikLeftCamera, hSmartWindowControl5));
                    }
                    else
                    {
                        continuousImage = false;
                        Task.WaitAll(GetImage_task_Hik);
                        continuousImage = true;
                        GetImage_task_Hik = Task.Run(() => CameraContinousImage(HikLeftCamera, hSmartWindowControl5));
                    }

                }
                if (comboBox1.SelectedItem.ToString() == "海康右" + configfil.HikRightCameraSeria)
                {

                    textBox1.Text = Convert.ToString(configfil.HikLeftCameraExposureTime);
                    if (GetImage_task_Hik == null)
                    {
                        continuousImage = true;
                        GetImage_task_Hik = Task.Run(() => CameraContinousImage(HikRightCamera, hSmartWindowControl5));
                    }
                    else
                    {
                        continuousImage = false;
                        Task.WaitAll(GetImage_task_Hik);
                        continuousImage = true;
                        GetImage_task_Hik = Task.Run(() => CameraContinousImage(HikRightCamera, hSmartWindowControl5));
                    }

                }
                for (int i = 0; i < configfil.CameraNames.Count; i++)
                {
                    if (comboBox1.SelectedItem.ToString() == "埃科" + configfil.CameraNames[i].CameraName)
                    {
                        //camera.detectDevice(true);
                        //camera.ConfigureFrameGrabber(OnFrameReadyFuncL, false, configfil.CameraNames[IkCameraNum].SerialNumber,"Left");
                        //IKapBoard.IKapStartGrab(camera.m_hBoardL, 0);
                        return;
                    }
                }
            }
            else { MessageBox.Show("请选择需要预览的相机"); }
        }

        private void button10_Click(object sender, EventArgs e)
        {
            if (comboBox1.SelectedItem != null)
            {
                if (comboBox1.SelectedItem.ToString() == "海康左" + configfil.HikLeftCameraSeria)
                {
                    continuousImage = false;
                    List<Bitmap> Imagelist = new List<Bitmap>();
                    continuousImage = false;
                    Bitmap Hikgetimage = null;
                    Thread.Sleep(100);
                    Hikgetimage = HikLeftCamera.GetImageBitMap();
                    ImageConvert.Bitmap2HObjectS(Hikgetimage, out HObject Hikgetimagewindow);
                    HOperatorSet.GetImageSize(Hikgetimagewindow, out HTuple Hikgetimagewindow_width, out HTuple Hikgetimagewindow_Height);
                    HOperatorSet.SetPart(hSmartWindowControl5.HalconWindow, 0, 0, Hikgetimagewindow_Height - 1, Hikgetimagewindow_width - 1);
                    HOperatorSet.DispObj(Hikgetimagewindow, hSmartWindowControl5.HalconWindow);
                    hSmartWindowControl5.SetFullImagePart();
                    Hikgetimagewindow_width.Dispose();
                    Hikgetimagewindow_Height.Dispose();
                    if (SaveImagecheck == true)
                    {
                        SaveImages("HikCamera", Hikgetimagewindow, "HikCamerLeft","OK", DateTime.Now.ToString("yyyy//MM//dd HH:mm:dd"));
                    }
                }
                if (comboBox1.SelectedItem.ToString() == "海康右" + configfil.HikRightCameraSeria)
                {
                    continuousImage = false;
                    List<Bitmap> Imagelist = new List<Bitmap>();
                    continuousImage = false;
                    Bitmap Hikgetimage = null;
                    Thread.Sleep(100);
                    Hikgetimage = HikRightCamera.GetImageBitMap();
                    ImageConvert.Bitmap2HObjectS(Hikgetimage, out HObject Hikgetimagewindow);
                    HOperatorSet.GetImageSize(Hikgetimagewindow, out HTuple Hikgetimagewindow_width, out HTuple Hikgetimagewindow_Height);
                    HOperatorSet.SetPart(hSmartWindowControl5.HalconWindow, 0, 0, Hikgetimagewindow_Height - 1, Hikgetimagewindow_width - 1);
                    HOperatorSet.DispObj(Hikgetimagewindow, hSmartWindowControl5.HalconWindow);
                    hSmartWindowControl5.SetFullImagePart();
                    Hikgetimagewindow_width.Dispose();
                    Hikgetimagewindow_Height.Dispose();
                    if (SaveImagecheck == true)
                    {
                        SaveImages("HikCamera", Hikgetimagewindow, "HikCameraRight", "OK", DateTime.Now.ToString("yyyy//MM//dd HH:mm:dd"));
                    }
                }
            }
            else { MessageBox.Show("请选择需要采图的相机"); }
        }

        private void label16_Click(object sender, EventArgs e)
        {

        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                configfil.StartLeft = textBox7.Text;
                configfil.End_Left = textBox8.Text;
                configfil.TestCodeReading_Left = textBox9.Text;
                configfil.TestMeasurement_Left = textBox10.Text;
                configfil.TestReult_Left = textBox11.Text;

                configfil.StartRight = textBox14.Text;
                configfil.End_Right = textBox15.Text;
                configfil.TestCodeReading_Right = textBox16.Text;
                configfil.TestMeasurement_Right = textBox17.Text;
                configfil.TestReult_Right = textBox18.Text;

                configfil.MinStartLeft = textBox12.Text;
                configfil.MinTestReult_Left = textBox19.Text;

                configfil.MinStartRight = textBox21.Text;
                configfil.MinTestReult_Right = textBox22.Text;

                configfil.PLCIpAddress = textBox13.Text;
                configfil.PLCPort = Convert.ToInt16(textBox6.Text);
                tool.SaveConfigFile(configfil);
                MessageBox.Show("设定成功");
            }
            catch (Exception ex)
            {
                MessageBox.Show("设定异常" + ex);
            }

        }

        private void button2_Click(object sender, EventArgs e)
        {
            Configurationfile = camera.ConfigureFrameGrabber(OnFrameReadyFuncR, true, configfil.CameraNames[IkCameraNum].SerialNumber, "Right");
            if (Configurationfile == true)
            {
                DisplayTxt(richTextBox1, "配置文件 " + configfil.RightConfigurationfilepath + "  已打开");
            }
            else { DisplayTxt(richTextBox1, "配置文件 " + configfil.RightConfigurationfilepath + "  打开异常"); }
            camera.SetFrameTrigger();
            ReadConfigfilState();
        }

        private void button16_Click(object sender, EventArgs e)
        {

        }

        private void button7_Click_1(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Title = "导入模板图片";
            openFileDialog.ShowDialog();
            if (openFileDialog.FileName != "")
            {
                HOperatorSet.ReadImage(out manualImage, openFileDialog.FileName);
                HOperatorSet.GetImageSize(manualImage, out HTuple width, out HTuple height);
                manualImage_width = width;
                manualImage_Height = height;
                HOperatorSet.DispObj(manualImage, hSmartWindowControl5.HalconWindow);
                hSmartWindowControl5.SetFullImagePart();
            }
        }

        private void button8_Click_1(object sender, EventArgs e)
        {
            if (DraROI != null) DraROI.ClearDrawingObject();
            DraROI = HDrawingObject.CreateDrawingObject(HDrawingObject.HDrawingObjectType.RECTANGLE1, 1000, 1000, 2000, 2000);
            DraROI.SetDrawingObjectParams("color", "green");
            hSmartWindowControl5.HalconWindow.AttachDrawingObjectToWindow(DraROI);
        }

        private void button12_Click(object sender, EventArgs e)
        {
            if (DraROI != null) DraROI.ClearDrawingObject();
            DraROI.Dispose();
        }

        private void button13_Click(object sender, EventArgs e)
        {
            if (DraROI != null)
            {
                if (DraROI.ID != 0)
                {
                    string[] str = new string[] { "row1", "column1", "row2", "column2" };
                    try
                    {
                        HTuple hTuple = DraROI.GetDrawingObjectParams(str);
                        HOperatorSet.GenRectangle1(out HObject ROI, hTuple.LArr[0], hTuple.LArr[1], hTuple.LArr[2], hTuple.LArr[3]);
                        Algorithm.Get_Radius(manualImage, ROI, out HObject Ho_Corcle, out HTuple radius, out HTuple Row, out HTuple Column);
                        HOperatorSet.SetColor(hSmartWindowControl5.HalconWindow, "red");
                        //DraROI.ClearDrawingObject();
                        HOperatorSet.DispRegion(Ho_Corcle, hSmartWindowControl5.HalconWindow);

                        Feature feature = new Feature();
                        feature._Style = Feature_Style.Circle;
                        //feature.Name = "区域" + productList.Product_list[Now_Product_ID].FeaturesList.Count;
                        feature.Name = GetName("区域", productList.Product_list[Now_Product_ID].FeaturesList.Count);
                        //feature.Region_Path = Directory.GetCurrentDirectory() + "\\Product\\" + productList.Product_list[Now_Product_ID].ProductName + "\\Region" + productList.Product_list[Now_Product_ID].FeaturesList.Count + ".hobj";
                        feature.Region_Path = Directory.GetCurrentDirectory() + "\\Product\\" + productList.Product_list[Now_Product_ID].ProductName + "\\" + feature.Name + ".hobj";
                        feature.Region_Path = feature.Region_Path.Replace("区域", "Region");
                        HOperatorSet.WriteRegion(ROI, feature.Region_Path);
                        productList.Product_list[Now_Product_ID].FeaturesList.Add(feature);
                        listBox1.Items.Add(feature.Name);

                    }
                    catch (Exception error)
                    {
                        MessageBox.Show(error.Message);
                    }
                    //DraROI.Dispose();
                }
            }

        }
        string GetName(string name, int index)
        {
            if (productList.Product_list[Now_Product_ID].FeaturesList.Find(x => x.Name == (name + index)) != null)
            {
                return GetName(name, ++index);
            }
            return name + index;

        }
        private void button19_Click(object sender, EventArgs e)
        {
            if (DraROI != null) DraROI.ClearDrawingObject();
            DraROI = HDrawingObject.CreateDrawingObject(HDrawingObject.HDrawingObjectType.LINE, 1000, 1000, 2000, 1000);
            DraROI.SetDrawingObjectParams("color", "green");
            hSmartWindowControl5.HalconWindow.AttachDrawingObjectToWindow(DraROI);
        }

        private void button20_Click(object sender, EventArgs e)
        {

            if (DraROI != null)
            {
                if (DraROI.ID != 0)
                {
                    string[] str = new string[] { "row1", "column1", "row2", "column2" };
                    HTuple hTuple = DraROI.GetDrawingObjectParams(str);
                    HOperatorSet.GenRegionLine(out HObject RetangleRegion, hTuple.LArr[0], hTuple.LArr[1], hTuple.LArr[2], hTuple.LArr[3]);
                    testRegion = RetangleRegion;
                    //DraROI.ClearDrawingObject();
                    HOperatorSet.SetColor(hSmartWindowControl5.HalconWindow, "yellow");
                    HOperatorSet.DispRegion(RetangleRegion, hSmartWindowControl5.HalconWindow);
                    Feature feature = new Feature();
                    feature._Style = Feature_Style.Line;
                    feature.Name = GetName("直线", productList.Product_list[Now_Product_ID].FeaturesList.Count);
                    //feature.Name = "直线" + productList.Product_list[Now_Product_ID].FeaturesList.Count;
                    feature.LineStartPoint.Row = hTuple.LArr[0];
                    feature.LineStartPoint.Column = hTuple.LArr[1];
                    feature.LineEndPoint.Row = hTuple.LArr[2];
                    feature.LineEndPoint.Column = hTuple.LArr[3];
                    //feature.Region_Path = Directory.GetCurrentDirectory() + "\\Product\\" + productList.Product_list[Now_Product_ID].ProductName + "\\Region" + productList.Product_list[Now_Product_ID].FeaturesList.Count + ".hobj";
                    feature.Region_Path = Directory.GetCurrentDirectory() + "\\Product\\" + productList.Product_list[Now_Product_ID].ProductName + "\\" + feature.Name + ".hobj";
                    feature.Region_Path = feature.Region_Path.Replace("直线", "Line");
                    HOperatorSet.WriteRegion(RetangleRegion, feature.Region_Path);
                    productList.Product_list[Now_Product_ID].FeaturesList.Add(feature);
                    listBox1.Items.Add(feature.Name);
                    //DraROI.Dispose();
                }
            }
            else
            {
                MessageBox.Show("未选择ROI工具");
            }


        }

        private void button21_Click(object sender, EventArgs e)
        {
            bool Is_Model1 = File.Exists(productList.Product_list[Now_Product_ID].StandraModel_Path1);
            bool Is_Model2 = File.Exists(productList.Product_list[Now_Product_ID].StandraModel_Path2);

            if (Is_Model1 == true && Is_Model2 == true)
            {
                HOperatorSet.ReadShapeModel(productList.Product_list[Now_Product_ID].StandraModel_Path1, out HTuple ModelID1);
                HOperatorSet.ReadShapeModel(productList.Product_list[Now_Product_ID].StandraModel_Path2, out HTuple ModelID2);
                Algorithm.Create_Stanrad_Point(manualImage, out HObject RegionLine, out HObject Circle_Region, ModelID1, ModelID2, out HTuple Row, out HTuple Column, out HTuple Angle);
                productList.Product_list[Now_Product_ID].Standard_Row = Row.D;
                productList.Product_list[Now_Product_ID].Standard_Column = Column.D;
                productList.Product_list[Now_Product_ID].Standard_Angle = Angle.D;
                HOperatorSet.DispRegion(RegionLine, hSmartWindowControl5.HalconWindow);
                HOperatorSet.DispRegion(Circle_Region, hSmartWindowControl5.HalconWindow);
            }
            else
            {
                MessageBox.Show("没有可以合并的模型");
            }
        }

        private void button22_Click(object sender, EventArgs e)
        {
            bool IsEmpty = false; //检测新建的产品名称是否存在
            Form2 form2 = new Form2();
            form2.ShowDialog();

            for (int i = 0; i < productList.Product_list.Count; i++)
            {
                if (form2.Name == productList.Product_list[i].ProductName) IsEmpty = true;
            }


            if (form2.Name != "" && IsEmpty == false)
            {
                Product product = new Product();
                product.ProductName = form2.Name;
                productList.Product_list.Add(product);
                comboBox2.Items.Add(form2.Name);
            }
            else
            {
                MessageBox.Show("该产品的名称已经存在或者输入名称不规范");
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            if (comboBox2.SelectedIndex > -1)
            {
                productList.Product_Now = productList.Product_list[comboBox2.SelectedIndex].ProductName;
                label54.Text = productList.Product_list[comboBox2.SelectedIndex].ProductName;
                Now_Product_ID = Find_Now_ID(productList);
                listBox1.Items.Clear();
                listBox2.Items.Clear();
                listBox8.Items.Clear();
                hSmartWindowControl1.HalconWindow.ClearWindow();
                hSmartWindowControl2.HalconWindow.ClearWindow();
                hSmartWindowControl3.HalconWindow.ClearWindow();
                hSmartWindowControl4.HalconWindow.ClearWindow();
                hSmartWindowControl5.HalconWindow.ClearWindow();
                hSmartWindowControl6.HalconWindow.ClearWindow();
                dataGridView1.Rows.Clear();
                dataGridView2.Rows.Clear();
                dataGridView3.Rows.Clear();
                dataGridView4.Rows.Clear();

                if (productList.Product_list[Now_Product_ID].FeaturesList.Count > 0)
                {
                    for (int i = 0; i < productList.Product_list[Now_Product_ID].FeaturesList.Count; i++)
                    {
                        listBox1.Items.Add(productList.Product_list[Now_Product_ID].FeaturesList[i].Name);
                    }
                }
                if (productList.Product_list[Now_Product_ID].MeasureList.Count > 0)
                {
                    for (int i = 0; i < productList.Product_list[Now_Product_ID].MeasureList.Count; i++)
                    {
                        if (productList.Product_list[Now_Product_ID].MeasureList[i].Name != "")
                        {
                            listBox2.Items.Add(productList.Product_list[Now_Product_ID].MeasureList[i].Name);
                        }
                        if (productList.Product_list[Now_Product_ID].MeasureList[i].PinName != "")
                        {
                            listBox2.Items.Add(productList.Product_list[Now_Product_ID].MeasureList[i].PinName);
                        }
                    }
                }
                if (productList.Product_list[Now_Product_ID].HikProductName != " ")
                {
                    listBox8.Items.Add(productList.Product_list[Now_Product_ID].HikProductName);
                }
                if (productList.Product_list[Now_Product_ID].Pinchek == true)
                {
                    checkBox2.Checked = true;
                    if (productList.Product_list[Now_Product_ID].LeftPinchekPos != "")
                    {
                        PLC.Write("R160", Convert.ToInt32(productList.Product_list[Now_Product_ID].LeftPinchekPos) * 1000);
                    }
                    if (productList.Product_list[Now_Product_ID].RightPinchekPos != "")
                    {
                        PLC.Write("R260", Convert.ToInt32(productList.Product_list[Now_Product_ID].RightPinchekPos) * 1000);
                    }
                }
                else 
                { 
                    checkBox2.Checked = false;
                    productList.Product_list[Now_Product_ID].LeftPinchekPos = (PLC.ReadInt32("R162").Content / 1000).ToString();
                    PLC.Write("R160", Convert.ToInt32(productList.Product_list[Now_Product_ID].LeftPinchekPos) * 1000);
                    productList.Product_list[Now_Product_ID].RightPinchekPos = (PLC.ReadInt32("R262").Content / 1000).ToString();
                    PLC.Write("R260", Convert.ToInt32(productList.Product_list[Now_Product_ID].RightPinchekPos) * 1000);
                }

                MessageBox.Show("设置成功");
            }
            else
            {
                MessageBox.Show("请选择对应的产品型号");
            }
        }

        private void button23_Click(object sender, EventArgs e)
        {

            try
            {
                
                HTuple scale = 4;
                HOperatorSet.ReadShapeModel(productList.Product_list[Now_Product_ID].StandraModel_Path1, out HTuple ModeID1);
                HOperatorSet.ReadRegion(out HObject modelRegion1, productList.Product_list[Now_Product_ID].ModelRegion_Path1);
                HOperatorSet.AreaCenter(modelRegion1, out HTuple area1, out HTuple row1, out HTuple column1);
                HOperatorSet.HomMat2dIdentity(out HTuple homMat2D1);
                HOperatorSet.HomMat2dScale(homMat2D1, scale, scale, row1, column1, out HTuple homMat2dScale1);
                HOperatorSet.AffineTransRegion(modelRegion1, out HObject regionAffineTrans1, homMat2dScale1, "nearest_neighbor");
                HOperatorSet.ReduceDomain(manualImage, regionAffineTrans1, out HObject image1);
                HOperatorSet.FindScaledShapeModel(image1, ModeID1, (new HTuple(-30)).TupleRad(), (new HTuple(30)).TupleRad(), 0.9, 1.1, 0.2, 1, 0.5, "least_squares", 0, 0.9, out HTuple Row1, out HTuple Column1, out HTuple Angle1, out HTuple Scale1, out HTuple Score1);
                HOperatorSet.GetShapeModelContours(out HObject ho_ModelContours1, ModeID1, 1);
                
                HOperatorSet.ReadShapeModel(productList.Product_list[Now_Product_ID].StandraModel_Path2, out HTuple ModeID2);
                HOperatorSet.ReadRegion(out HObject modelRegion2, productList.Product_list[Now_Product_ID].ModelRegion_Path2);
                HOperatorSet.AreaCenter(modelRegion2, out HTuple area2, out HTuple row2, out HTuple column2);
                HOperatorSet.HomMat2dIdentity(out HTuple homMat2D2);
                HOperatorSet.HomMat2dScale(homMat2D2, scale, scale, row2, column2, out HTuple homMat2dScale2);
                HOperatorSet.AffineTransRegion(modelRegion2, out HObject regionAffineTrans2, homMat2dScale2, "nearest_neighbor");
                HOperatorSet.ReduceDomain(manualImage, regionAffineTrans2, out HObject image2);
                HOperatorSet.FindScaledShapeModel(image2, ModeID2, (new HTuple(-30)).TupleRad(), (new HTuple(30)).TupleRad(), 0.9, 1.1, 0.2, 1, 0.5, "least_squares", 0, 0.9, out HTuple Row2, out HTuple Column2, out HTuple Angle2, out HTuple Scale2, out HTuple Score2);
                HOperatorSet.GetShapeModelContours(out HObject ho_ModelContours2, ModeID2, 1);
                if (Score1.Length > 0 && Score1.Length > 0)
                {
                    HOperatorSet.HomMat2dIdentity(out HTuple HomMat2DIdentity1);
                    HOperatorSet.HomMat2dTranslate(HomMat2DIdentity1, Row1, Column1, out HTuple HomMat2DTranslate1);
                    HOperatorSet.HomMat2dRotateLocal(HomMat2DTranslate1, Angle1, out HTuple HomMat2DRotate1);
                    HOperatorSet.AffineTransContourXld(ho_ModelContours1, out HObject ContoursAffineTrans1, HomMat2DRotate1);

                    HOperatorSet.HomMat2dIdentity(out HTuple HomMat2DIdentity2);
                    HOperatorSet.HomMat2dTranslate(HomMat2DIdentity2, Row2, Column2, out HTuple HomMat2DTranslate2);
                    HOperatorSet.HomMat2dRotateLocal(HomMat2DTranslate2, Angle2, out HTuple HomMat2DRotate2);
                    HOperatorSet.AffineTransContourXld(ho_ModelContours2, out HObject ContoursAffineTrans2, HomMat2DRotate2);

                    HOperatorSet.SetColor(hSmartWindowControl5.HalconWindow, "red");
                    HOperatorSet.DispXld(ContoursAffineTrans1, hSmartWindowControl5.HalconWindow);
                    HOperatorSet.DispXld(ContoursAffineTrans2, hSmartWindowControl5.HalconWindow);
                }
                else
                {
                    MessageBox.Show("没有找到对应的基准点");
                }
            }
            catch (Exception error)
            {
                MessageBox.Show("验证失败!" + error.Message);
            }

        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                HTuple HomMat2DTranslate = new HTuple();
                bool Is_Model1 = File.Exists(productList.Product_list[Now_Product_ID].StandraModel_Path1);
                bool Is_Model2 = File.Exists(productList.Product_list[Now_Product_ID].StandraModel_Path2);
                bool Is_ModelRegion1 = File.Exists(productList.Product_list[Now_Product_ID].ModelRegion_Path1);
                bool Is_ModelRegion2 = File.Exists(productList.Product_list[Now_Product_ID].ModelRegion_Path2);
                if (Is_Model1 == true && Is_Model2 == true)
                {
                    HTuple scale = 4;
                    HTuple Row = 0;
                    HTuple Column = 0;
                    HTuple Angle = 0;
                    Measure measure = new Measure(manualImage_width, manualImage_Height);
                    HOperatorSet.ReadShapeModel(productList.Product_list[Now_Product_ID].StandraModel_Path1, out HTuple ModelID1);
                    HOperatorSet.ReadShapeModel(productList.Product_list[Now_Product_ID].StandraModel_Path2, out HTuple ModelID2);
                    if (Is_ModelRegion1 && Is_ModelRegion2)
                    {
                        HOperatorSet.ReadRegion(out HObject modelRegion1, productList.Product_list[Now_Product_ID].ModelRegion_Path1);
                        HOperatorSet.AreaCenter(modelRegion1, out HTuple area1, out HTuple row1, out HTuple column1);
                        HOperatorSet.HomMat2dIdentity(out HTuple homMat2D1);
                        HOperatorSet.HomMat2dScale(homMat2D1, scale, scale, row1, column1, out HTuple homMat2dScale1);
                        HOperatorSet.AffineTransRegion(modelRegion1, out HObject regionAffineTrans1, homMat2dScale1, "nearest_neighbor");
                        HOperatorSet.ReduceDomain(manualImage, regionAffineTrans1, out HObject image1);

                        HOperatorSet.ReadRegion(out HObject modelRegion2, productList.Product_list[Now_Product_ID].ModelRegion_Path2);
                        HOperatorSet.AreaCenter(modelRegion2, out HTuple area2, out HTuple row2, out HTuple column2);
                        HOperatorSet.HomMat2dIdentity(out HTuple homMat2D2);
                        HOperatorSet.HomMat2dScale(homMat2D2, scale, scale, row2, column2, out HTuple homMat2dScale2);
                        HOperatorSet.AffineTransRegion(modelRegion2, out HObject regionAffineTrans2, homMat2dScale2, "nearest_neighbor");
                        HOperatorSet.ReduceDomain(manualImage, regionAffineTrans2, out HObject image2);

                        //HOperatorSet.DispObj(regionAffineTrans1, hSmartWindowControl1.HalconWindow);
                        //HOperatorSet.DispObj(regionAffineTrans2, hSmartWindowControl1.HalconWindow);

                        Algorithm.Create_Stanrad_Point(image1, image2, out HObject RegionLine, out HObject Circle_Region, ModelID1, ModelID2, out Row, out Column, out Angle);

                    }
                    else
                        Algorithm.Create_Stanrad_Point(manualImage, out HObject RegionLine, out HObject Circle_Region, ModelID1, ModelID2, out  Row, out  Column, out  Angle);
                    double Rotation_Center = Angle.D - productList.Product_list[Now_Product_ID].Standard_Angle;
                    if (Rotation_Center > 3) Rotation_Center = Rotation_Center - 3.1415;
                    if (Rotation_Center < -3) Rotation_Center = Rotation_Center + 3.1415;
                    HOperatorSet.VectorAngleToRigid(productList.Product_list[Now_Product_ID].Standard_Row, productList.Product_list[Now_Product_ID].Standard_Column, 0, Row, Column, Rotation_Center, out HomMat2DTranslate);


                    HOperatorSet.GenImageConst(out HObject H_region, "byte", manualImage_width, manualImage_Height);
                    HOperatorSet.SetDraw(hSmartWindowControl5.HalconWindow, "margin");
                    if (listBox1.SelectedIndex > -1)
                    {
                        if (listBox1.SelectedItem.ToString() == "PIN区域")
                        {
                            return;
                        }
                        if (productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.Circle)
                        {
                            HOperatorSet.ReadRegion(out H_region, productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex].Region_Path);
                            HOperatorSet.SetColor(hSmartWindowControl5.HalconWindow, "green");
                            HOperatorSet.AreaCenter(H_region, out HTuple Area, out HTuple Row1, out HTuple Column1);
                            HOperatorSet.DispText(hSmartWindowControl5.HalconWindow, productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex].Name, "image", Row1, Column1, "red", "box", "false");
                            HOperatorSet.AffineTransRegion(H_region, out HObject regionAffineTrans, HomMat2DTranslate, "nearest_neighbor");
                            HOperatorSet.DispRegion(regionAffineTrans, hSmartWindowControl5.HalconWindow);
                        }
                        if (productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.LineXY)
                        {
                            HOperatorSet.GenImageConst(out HObject H_Line_Region, "byte", manualImage_width, manualImage_Height);
                            HOperatorSet.ReadRegion(out H_Line_Region, productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex].Region_Path);
                            HOperatorSet.AffineTransRegion(H_Line_Region, out HObject regionAffineTrans, HomMat2DTranslate, "nearest_neighbor");
                            HOperatorSet.SmallestRectangle1(regionAffineTrans, out HTuple A_Row1, out HTuple A_Column1, out HTuple A_Row2, out HTuple A_Column2);
                            if (productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex].Name.Contains("基准轴"))
                            {

                                //计算轴线
                                //Feature feature1 = productList.Product_list[Now_Product_ID].FeaturesList.Find(x => x.Name.Contains("基准轴") && x.Name.Contains(","));

                                //基准轴线
                                string pointName1 = productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex].Name.Split('_')[1].Split(',')[0];
                                string pointName2 = productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex].Name.Split('_')[1].Split(',')[1];
                                if (pointName1 != "" && pointName2 != "")
                                {
                                    Feature feature3 = productList.Product_list[Now_Product_ID].FeaturesList.Find(x => x.Name == pointName1);
                                    Feature feature4 = productList.Product_list[Now_Product_ID].FeaturesList.Find(x => x.Name == pointName2);

                                    double row1 = 0;
                                    double col1 = 0;
                                    double row2 = 0;
                                    double col2 = 0;
                                    HOperatorSet.ReadRegion(out HObject region1, feature3.Region_Path);
                                    HOperatorSet.AffineTransRegion(region1, out HObject region1_Afftrance, HomMat2DTranslate, "nearest_neighbor");
                                    switch (feature3._Style)
                                    {
                                        case Feature_Style.Circle:
                                            Algorithm.Get_Radius(manualImage, region1_Afftrance, out HObject circle1, out HTuple radius1, out HTuple hv_Row1, out HTuple hv_Col1);
                                            row1 = hv_Row1.D;
                                            col1 = hv_Col1.D;
                                            break;
                                        case Feature_Style.Line:
                                            break;
                                        case Feature_Style.ReadCode:
                                            break;
                                        case Feature_Style.SemiCircle:
                                            break;
                                        case Feature_Style.ellipse:
                                            break;
                                    }
                                    HOperatorSet.ReadRegion(out HObject region2, feature4.Region_Path);
                                    HOperatorSet.AffineTransRegion(region2, out HObject region2_Afftrance, HomMat2DTranslate, "nearest_neighbor");
                                    switch (feature4._Style)
                                    {
                                        case Feature_Style.Circle:
                                            Algorithm.Get_Radius(manualImage, region2_Afftrance, out HObject circle2, out HTuple radius2, out HTuple hv_Row2, out HTuple hv_Col2);
                                            row2 = hv_Row2.D;
                                            col2 = hv_Col2.D;
                                            break;
                                        case Feature_Style.Line:
                                            break;
                                        case Feature_Style.ReadCode:
                                            break;
                                        case Feature_Style.SemiCircle:
                                            break;
                                        case Feature_Style.ellipse:
                                            break;
                                    }
                                    HOperatorSet.GenRegionLine(out HObject regionline1, row1, col1, row2, col2);
                                    //Algorithm.GetlineL(row1, col1, row2, col2, out HTuple hv_Deg1, out HTuple hv_RowStart1, out HTuple hv_ColStart1, out HTuple hv_RowEnd1, out HTuple hv_ColEnd1);
                                    //HOperatorSet.GenRegionLine(out HObject regionline1L, hv_RowStart1, hv_ColStart1, hv_RowEnd1, hv_ColEnd1);
                                    HOperatorSet.DispText(hSmartWindowControl5.HalconWindow, productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex].Name, "image", (productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex].LineStartPoint.Row + productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex].LineEndPoint.Row) / 2, (productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex].LineStartPoint.Column + productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex].LineEndPoint.Column) / 2, "red", "box", "false");
                                    HOperatorSet.SetColor(hSmartWindowControl5.HalconWindow, "red");
                                    HOperatorSet.DispObj(regionline1, hSmartWindowControl5.HalconWindow);
                                    //投影轴线
                                    Feature feature2 = productList.Product_list[Now_Product_ID].FeaturesList.Find(x => x.Name.Contains("基准轴") && !x.Name.Contains(","));
                                    if (feature2 == null)
                                    {
                                        return;
                                    }
                                    string pointName3 = feature2.Name.Split('_')[1];
                                    Feature feature5 = productList.Product_list[Now_Product_ID].FeaturesList.Find(x => x.Name == pointName3);
                                    double row3 = 0;
                                    double col3 = 0;
                                    HOperatorSet.ReadRegion(out HObject region3, feature5.Region_Path);
                                    HOperatorSet.AffineTransRegion(region3, out HObject region3_Afftrance, HomMat2DTranslate, "nearest_neighbor");
                                    switch (feature5._Style)
                                    {
                                        case Feature_Style.Circle:
                                            Algorithm.Get_Radius(manualImage, region3_Afftrance, out HObject circle3, out HTuple radius3, out HTuple hv_Row3, out HTuple hv_Col3);
                                            row3 = hv_Row3.D;
                                            col3 = hv_Col3.D;
                                            break;
                                        case Feature_Style.Line:
                                            break;
                                        case Feature_Style.ReadCode:
                                            break;
                                        case Feature_Style.SemiCircle:
                                            break;
                                        case Feature_Style.ellipse:
                                            break;
                                    }

                                    HOperatorSet.ProjectionPl(row3, col3, row1, col1, row2, col2, out HTuple rowProj, out HTuple colProj);
                                    HOperatorSet.GenRegionLine(out HObject regionline2, row3, col3, rowProj, colProj);
                                    //Algorithm.GetlineL(row3, col3, rowProj, colProj, out HTuple hv_Deg2, out HTuple hv_RowStart2, out HTuple hv_ColStart2, out HTuple hv_RowEnd2, out HTuple hv_ColEnd2);
                                    //HOperatorSet.GenRegionLine(out HObject regionline2L, hv_RowStart2, hv_ColStart2, hv_RowEnd2, hv_ColEnd2);
                                    HOperatorSet.DispObj(regionline2, hSmartWindowControl5.HalconWindow);
                                    HOperatorSet.DispText(hSmartWindowControl5.HalconWindow, productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex + 1].Name, "image", (productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex + 1].LineStartPoint.Row + productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex + 1].LineEndPoint.Row) / 2, (productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex + 1].LineStartPoint.Column + productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex + 1].LineEndPoint.Column) / 2, "red", "box", "false");
                                }
                            }
                        }

                        if (productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.ReadCode)
                        {
                            HOperatorSet.ReadRegion(out H_region, productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex].Region_Path);
                            HOperatorSet.SetColor(hSmartWindowControl5.HalconWindow, "blue");
                            HOperatorSet.DispRegion(H_region, hSmartWindowControl5.HalconWindow);
                            HOperatorSet.AreaCenter(H_region, out HTuple Area, out HTuple Row2, out HTuple Column2);
                            HOperatorSet.DispText(hSmartWindowControl5.HalconWindow, productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex].Name, "image", Row2, Column2, "red", "box", "false");
                            HOperatorSet.DispRegion(H_region, hSmartWindowControl5.HalconWindow);
                        }

                        if (productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.SemiCircle)
                        {
                            HOperatorSet.ReadRegion(out H_region, productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex].Region_Path);
                            HOperatorSet.SetColor(hSmartWindowControl5.HalconWindow, "green");
                            HOperatorSet.AreaCenter(H_region, out HTuple Area, out HTuple Row3, out HTuple Column3);
                            HOperatorSet.DispText(hSmartWindowControl5.HalconWindow, productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex].Name, "image", Row3, Column3, "red", "box", "false");
                            HOperatorSet.DispRegion(H_region, hSmartWindowControl5.HalconWindow);
                        }
                        if (productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.ellipse)
                        {
                            HOperatorSet.ReadRegion(out H_region, productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex].Region_Path);
                            HOperatorSet.SetColor(hSmartWindowControl5.HalconWindow, "green");
                            HOperatorSet.AreaCenter(H_region, out HTuple Area, out HTuple Row1, out HTuple Column1);
                            HOperatorSet.DispText(hSmartWindowControl5.HalconWindow, productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex].Name, "image", Row1, Column1, "red", "box", "false");
                            HOperatorSet.AffineTransRegion(H_region, out HObject regionAffineTrans, HomMat2DTranslate, "nearest_neighbor");
                            HOperatorSet.DispRegion(regionAffineTrans, hSmartWindowControl5.HalconWindow);
                        }

                        if (productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.Line)
                        {
                            HOperatorSet.GenImageConst(out HObject H_Line_Region, "byte", manualImage_width, manualImage_Height);
                            HOperatorSet.ReadRegion(out H_Line_Region, productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex].Region_Path);
                            HOperatorSet.AffineTransRegion(H_Line_Region, out HObject regionAffineTrans, HomMat2DTranslate, "nearest_neighbor");
                            HOperatorSet.SmallestRectangle1(regionAffineTrans, out HTuple A_Row1, out HTuple A_Column1, out HTuple A_Row2, out HTuple A_Column2);
                            if (productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex].Name.Contains("点构线"))
                            {

                                //计算轴线
                                Feature feature1 = productList.Product_list[Now_Product_ID].FeaturesList.Find(x => x.Name.Contains("点构线") && x.Name.Contains(","));

                                //基准轴线
                                string pointName1 = feature1.Name.Split('_')[1].Split(',')[0];
                                string pointName2 = feature1.Name.Split('_')[1].Split(',')[1];
                                Feature feature3 = productList.Product_list[Now_Product_ID].FeaturesList.Find(x => x.Name == pointName1);
                                Feature feature4 = productList.Product_list[Now_Product_ID].FeaturesList.Find(x => x.Name == pointName2);

                                double row1 = 0;
                                double col1 = 0;
                                double row2 = 0;
                                double col2 = 0;
                                HOperatorSet.ReadRegion(out HObject region1, feature3.Region_Path);
                                HOperatorSet.AffineTransRegion(region1, out HObject region1_Afftrance, HomMat2DTranslate, "nearest_neighbor");
                                switch (feature3._Style)
                                {
                                    case Feature_Style.Circle:
                                        Algorithm.Get_Radius(manualImage, region1_Afftrance, out HObject circle1, out HTuple radius1, out HTuple hv_Row1, out HTuple hv_Col1);
                                        row1 = hv_Row1.D;
                                        col1 = hv_Col1.D;
                                        break;
                                    case Feature_Style.Line:
                                        break;
                                    case Feature_Style.ReadCode:
                                        break;
                                    case Feature_Style.SemiCircle:
                                        break;
                                    case Feature_Style.ellipse:
                                        break;
                                }
                                HOperatorSet.ReadRegion(out HObject region2, feature4.Region_Path);
                                HOperatorSet.AffineTransRegion(region2, out HObject region2_Afftrance, HomMat2DTranslate, "nearest_neighbor");
                                switch (feature4._Style)
                                {
                                    case Feature_Style.Circle:
                                        Algorithm.Get_Radius(manualImage, region2_Afftrance, out HObject circle2, out HTuple radius2, out HTuple hv_Row2, out HTuple hv_Col2);
                                        row2 = hv_Row2.D;
                                        col2 = hv_Col2.D;
                                        break;
                                    case Feature_Style.Line:
                                        break;
                                    case Feature_Style.ReadCode:
                                        break;
                                    case Feature_Style.SemiCircle:
                                        break;
                                    case Feature_Style.ellipse:
                                        break;
                                }
                                HOperatorSet.GenRegionLine(out HObject regionline1, row1, col1, row2, col2);
                                //Algorithm.GetlineL(row1, col1, row2, col2, out HTuple hv_Deg1, out HTuple hv_RowStart1, out HTuple hv_ColStart1, out HTuple hv_RowEnd1, out HTuple hv_ColEnd1);
                                //HOperatorSet.GenRegionLine(out HObject regionline1L, hv_RowStart1, hv_ColStart1, hv_RowEnd1, hv_ColEnd1);
                                HOperatorSet.DispText(hSmartWindowControl5.HalconWindow, productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex].Name, "image", (productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex].LineStartPoint.Row + productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex].LineEndPoint.Row) / 2, (productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex].LineStartPoint.Column + productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex].LineEndPoint.Column) / 2, "red", "box", "false");
                                HOperatorSet.SetColor(hSmartWindowControl5.HalconWindow, "red");
                                HOperatorSet.DispObj(regionline1, hSmartWindowControl5.HalconWindow);
                            }
                            else
                            {
                                Algorithm.GetLine(manualImage, 1000, 50, A_Row1, A_Column1, A_Row2, A_Column2, out HTuple B_Row1, out HTuple B_Column1, out HTuple B_Row2, out HTuple B_Column2);
                                HOperatorSet.GenRegionLine(out HObject LineRegion_B, B_Row1, B_Column1, B_Row2, B_Column2);
                                HOperatorSet.SetColor(hSmartWindowControl5.HalconWindow, "red");
                                HOperatorSet.DispRegion(LineRegion_B, hSmartWindowControl5.HalconWindow);
                                HOperatorSet.DispText(hSmartWindowControl5.HalconWindow, productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex].Name, "image", (productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex].LineStartPoint.Row + productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex].LineEndPoint.Row) / 2, (productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex].LineStartPoint.Column + productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex].LineEndPoint.Column) / 2, "red", "box", "false");
                            }

                        }
                    }
                }
            }
            catch
            {

            }
        }

        private void button24_Click(object sender, EventArgs e)
        {
            
            if (listBox1.SelectedIndex > -1)
            {
                if (productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.LineXY|| productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.LineRC)
                {
                    if (productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex].Name.Contains("基准轴"))
                    {
                        int FeaturesList_Count= productList.Product_list[Now_Product_ID].FeaturesList.Count;
                        for (int i = 0; i < FeaturesList_Count; i++)
                        {
                            if (productList.Product_list[Now_Product_ID].FeaturesList[i].Name.Contains("基准轴"))
                            {
                                productList.Product_list[Now_Product_ID].FeaturesList.RemoveAt(i);
                                listBox1.Items.RemoveAt(i);
                                FeaturesList_Count--;
                                i--;
                            }
                        }
                        MessageBox.Show("基准轴删除成功");
                        return;
                    }
                 }
                productList.Product_list[Now_Product_ID].FeaturesList.RemoveAt(listBox1.SelectedIndex);
                listBox1.Items.RemoveAt(listBox1.SelectedIndex);
                MessageBox.Show("删除成功");
            }
        }

        private void button25_Click(object sender, EventArgs e)
        {
            if (DraROI != null)
            {
                string[] str = new string[] { "row1", "column1", "row2", "column2" };
                try
                {
                    HTuple hTuple = DraROI.GetDrawingObjectParams(str);
                    HOperatorSet.GenRectangle1(out HObject ROI, hTuple.LArr[0], hTuple.LArr[1], hTuple.LArr[2], hTuple.LArr[3]);
                    Algorithm.Get_Radius(manualImage, ROI, out HObject Ho_Corcle, out HTuple radius, out HTuple Row, out HTuple Column);
                    HOperatorSet.SetColor(hSmartWindowControl5.HalconWindow, "red");
                    DraROI.ClearDrawingObject();
                    HOperatorSet.DispRegion(Ho_Corcle, hSmartWindowControl5.HalconWindow);

                    Feature feature = new Feature();
                    feature._Style = Feature_Style.ReadCode;
                    feature.Name = GetName("读码", productList.Product_list[Now_Product_ID].FeaturesList.Count);
                    //feature.Region_Path = Directory.GetCurrentDirectory() + "\\Product\\" + productList.Product_list[Now_Product_ID].ProductName + "\\Region" + productList.Product_list[Now_Product_ID].FeaturesList.Count + ".hobj";
                    feature.Region_Path = Directory.GetCurrentDirectory() + "\\Product\\" + productList.Product_list[Now_Product_ID].ProductName + "\\" + feature.Name + ".hobj";
                    feature.Region_Path = feature.Region_Path.Replace("读码", "ReadCode");
                    HOperatorSet.WriteRegion(ROI, feature.Region_Path);
                    productList.Product_list[Now_Product_ID].FeaturesList.Add(feature);
                    listBox1.Items.Add(feature.Name);

                }
                catch (Exception error)
                {
                    MessageBox.Show(error.Message);
                }
            }
            else
            {
                MessageBox.Show("未选择ROI工具");
            }
        }

        private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox3.SelectedIndex > -1)
            {
                tabControl2.SelectedIndex = comboBox3.SelectedIndex;
            }
        }

        private void button29_Click(object sender, EventArgs e)
        {
            if (productList.Product_list[Now_Product_ID].FeaturesList.Count > 0)
            {
                for (int i = 0; i < productList.Product_list[Now_Product_ID].FeaturesList.Count; i++)
                {
                    if (productList.Product_list[Now_Product_ID].FeaturesList[i]._Style == Feature_Style.ReadCode)
                    {
                        HOperatorSet.GenImageConst(out HObject H_region, "byte", manualImage_width, manualImage_Height);
                        HOperatorSet.ReadRegion(out H_region, productList.Product_list[Now_Product_ID].FeaturesList[i].Region_Path);
                        Algorithm.Read_Data_Code(manualImage, H_region, out HObject symbolXLD, out HTuple CodeStr);

                        if (CodeStr.Length == 0)
                        {
                            Algorithm.ReadBar_Code(manualImage, H_region, out symbolXLD, out CodeStr);
                            HOperatorSet.AreaCenter(H_region, out HTuple Area1, out HTuple Row1, out HTuple Column1);
                            HOperatorSet.SetColor(hSmartWindowControl5.HalconWindow, "blue");
                            HOperatorSet.DispRegion(symbolXLD, hSmartWindowControl5.HalconWindow);
                            if (CodeStr.Length != 0)
                            {
                                HOperatorSet.DispText(hSmartWindowControl5.HalconWindow, "二维码:" + CodeStr.S, "image", Row1, Column1, "red", "box", "false");
                            }
                            return;
                        }
                        HOperatorSet.SetColor(hSmartWindowControl5.HalconWindow, "blue");
                        HOperatorSet.AreaCenterXld(symbolXLD, out HTuple Area, out HTuple Row, out HTuple Column, out HTuple PointOrder);
                        HOperatorSet.DispXld(symbolXLD, hSmartWindowControl5.HalconWindow);
                        if (CodeStr.Length != 0)
                        {
                            HOperatorSet.DispText(hSmartWindowControl5.HalconWindow, "二维码:" + CodeStr.S, "image", Row, Column, "red", "box", "false");
                        }


                    }
                }
            }
        }

        private void button30_Click(object sender, EventArgs e)
        {
            if (listBox1.SelectedIndex > -1)
            {
                if (productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.Circle || productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.SemiCircle)
                {
                    textBox27.Text = listBox1.SelectedItem.ToString();
                }
                else
                {
                    MessageBox.Show("选择的特征类型错误");
                }

            }
        }

        private void button31_Click(object sender, EventArgs e)
        {
            if (listBox1.SelectedIndex > -1)
            {



                if (productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.Circle || productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.SemiCircle)
                {
                    textBox28.Text = listBox1.SelectedItem.ToString();
                }
                else
                {
                    MessageBox.Show("选择的特征类型错误");
                }

            }
        }

        private void button26_Click(object sender, EventArgs e)
        {
            string str = "";
            Measure_Tool measure_Tool = new Measure_Tool();
            if (listBox1.SelectedIndex > -1)
            {
                try
                {
                    switch (comboBox3.SelectedIndex)
                    {
                        case 0:
                            str = "点到点量测:" + textBox27.Text + "→" + textBox28.Text;
                            measure_Tool.Name = str;
                            measure_Tool.MeasureFeature1 = FindFeature(textBox27.Text);
                            measure_Tool.MeasureFeature2 = FindFeature(textBox28.Text);
                            measure_Tool.Measure_Style = Measure_Style.Point_To_Point;
                            measure_Tool.SetValue = Convert.ToDouble(textBox87.Text);
                            if (CompensationValueL == true)
                            {
                                measure_Tool.CompensationValueLeft = Convert.ToDouble(textBox88.Text);
                            }
                            if (CompensationValueR == true)
                            {
                                measure_Tool.CompensationValueRight = Convert.ToDouble(textBox88.Text);
                            }
                            measure_Tool.PositiveValue = Convert.ToDouble(textBox29.Text);
                            measure_Tool.NegativeValue = Convert.ToDouble(textBox30.Text);
                            measure_Tool.MaxValue = measure_Tool.SetValue + measure_Tool.PositiveValue;
                            measure_Tool.MinValue = measure_Tool.SetValue - measure_Tool.NegativeValue;
                            productList.Product_list[Now_Product_ID].MeasureList.Add(measure_Tool);
                            listBox2.Items.Add(str);
                            break;
                        case 1:
                            str = "点到边量测:" + textBox31.Text + "→" + textBox32.Text;
                            measure_Tool.Name = str;
                            measure_Tool.MeasureFeature1 = FindFeature(textBox31.Text);
                            measure_Tool.MeasureFeature2 = FindFeature(textBox32.Text);
                            measure_Tool.Measure_Style = Measure_Style.Point_To_Line;
                            measure_Tool.SetValue = Convert.ToDouble(textBox90.Text);
                            if (CompensationValueL == true)
                            {
                                measure_Tool.CompensationValueLeft = Convert.ToDouble(textBox89.Text);
                            }
                            if (CompensationValueR == true)
                            {
                                measure_Tool.CompensationValueRight = Convert.ToDouble(textBox89.Text);
                            }
                            measure_Tool.PositiveValue = Convert.ToDouble(textBox33.Text);
                            measure_Tool.NegativeValue = Convert.ToDouble(textBox34.Text);
                            measure_Tool.MaxValue = measure_Tool.SetValue + measure_Tool.PositiveValue;
                            measure_Tool.MinValue = measure_Tool.SetValue - measure_Tool.NegativeValue;
                            productList.Product_list[Now_Product_ID].MeasureList.Add(measure_Tool);
                            listBox2.Items.Add(str);
                            break;
                        case 2:
                            str = "边到边量测:" + textBox35.Text + "→" + textBox39.Text;
                            measure_Tool.Name = str;
                            measure_Tool.MeasureFeature1 = FindFeature(textBox35.Text);
                            measure_Tool.MeasureFeature2 = FindFeature(textBox36.Text);
                            measure_Tool.MeasureFeature3 = FindFeature(textBox39.Text);
                            measure_Tool.Measure_Style = Measure_Style.Line_To_Line;
                            measure_Tool.SetValue = Convert.ToDouble(textBox92.Text);
                            if (CompensationValueL == true)
                            {
                                measure_Tool.CompensationValueLeft = Convert.ToDouble(textBox91.Text);
                            }
                            if (CompensationValueR == true)
                            {
                                measure_Tool.CompensationValueRight = Convert.ToDouble(textBox91.Text);
                            }
                            measure_Tool.PositiveValue = Convert.ToDouble(textBox37.Text);
                            measure_Tool.NegativeValue = Convert.ToDouble(textBox38.Text);
                            measure_Tool.MaxValue = measure_Tool.SetValue + measure_Tool.PositiveValue;
                            measure_Tool.MinValue = measure_Tool.SetValue - measure_Tool.NegativeValue;
                            productList.Product_list[Now_Product_ID].MeasureList.Add(measure_Tool);
                            listBox2.Items.Add(str);
                            break;
                        case 3:
                            str = "螺丝监督:" + textBox40.Text;
                            measure_Tool.Name = str;
                            measure_Tool.MeasureFeature1 = FindFeature(textBox40.Text);
                            measure_Tool.Measure_Style = Measure_Style.Screw;
                            productList.Product_list[Now_Product_ID].MeasureList.Add(measure_Tool);
                            listBox2.Items.Add(str);
                            break;
                        case 4:
                            str = "读码:" + textBox41.Text;
                            measure_Tool.Name = str;
                            measure_Tool.MeasureFeature1 = FindFeature(textBox41.Text);
                            measure_Tool.Measure_Style = Measure_Style.ReadCode;
                            if (radioButton1.Checked == true) measure_Tool.Code_Style = Code_Style.bar_Code;
                            if (radioButton2.Checked == true) measure_Tool.Code_Style = Code_Style.QR_Code1;
                            if (radioButton3.Checked == true) measure_Tool.Code_Style = Code_Style.QR_Code2;
                            if (radioButton1.Checked == false && radioButton2.Checked == false && radioButton3.Checked == false) measure_Tool.Code_Style = Code_Style.QR_Code1;
                            productList.Product_list[Now_Product_ID].MeasureList.Add(measure_Tool);
                            listBox2.Items.Add(str);

                            radioButton1.Checked = false;
                            radioButton2.Checked = false;
                            radioButton3.Checked = false;
                            break;
                        case 5:
                            str = "测量孔直径:" + textBox42.Text;
                            measure_Tool.Name = str;
                            measure_Tool.MeasureFeature1 = FindFeature(textBox42.Text);
                            measure_Tool.Measure_Style = Measure_Style.Circle_Measure;
                            measure_Tool.SetValue = Convert.ToDouble(textBox94.Text);
                            if (CompensationValueL == true)
                            {
                                measure_Tool.CompensationValueLeft = Convert.ToDouble(textBox93.Text);
                            }
                            if (CompensationValueR == true)
                            {
                                measure_Tool.CompensationValueRight = Convert.ToDouble(textBox93.Text);
                            }
                            measure_Tool.PositiveValue = Convert.ToDouble(textBox43.Text);
                            measure_Tool.NegativeValue = Convert.ToDouble(textBox44.Text);
                            measure_Tool.MaxValue = measure_Tool.SetValue + measure_Tool.PositiveValue;
                            measure_Tool.MinValue = measure_Tool.SetValue - measure_Tool.NegativeValue;
                            productList.Product_list[Now_Product_ID].MeasureList.Add(measure_Tool);
                            listBox2.Items.Add(str);
                            break;
                        case 7:
                            str = "投影测量:" + textBox83.Text + "→" + textBox82.Text;
                            measure_Tool.Name = str;
                            measure_Tool.Measure_Style = Measure_Style.Projection;
                            measure_Tool.MeasureFeature1 = FindFeature(textBox81.Text);
                            measure_Tool.MeasureFeature2 = FindFeature(textBox83.Text);
                            measure_Tool.MeasureFeature3 = FindFeature(textBox82.Text);
                            measure_Tool.SetValue = Convert.ToDouble(textBox96.Text);
                            if (CompensationValueL == true)
                            {
                                measure_Tool.CompensationValueLeft = Convert.ToDouble(textBox95.Text);
                            }
                            if (CompensationValueR == true)
                            {
                                measure_Tool.CompensationValueRight = Convert.ToDouble(textBox95.Text);
                            }
                            measure_Tool.PositiveValue = Convert.ToDouble(textBox84.Text);
                            measure_Tool.NegativeValue = Convert.ToDouble(textBox85.Text);
                            measure_Tool.MaxValue = measure_Tool.SetValue + measure_Tool.PositiveValue;
                            measure_Tool.MinValue = measure_Tool.SetValue - measure_Tool.NegativeValue;
                            productList.Product_list[Now_Product_ID].MeasureList.Add(measure_Tool);
                            listBox2.Items.Add(str);
                            break;
                        case 8:
                            str = "椭圆测量:" + textBox109.Text;
                            measure_Tool.Name = str;
                            measure_Tool.Measure_Style = Measure_Style.Ellipse;
                            measure_Tool.MeasureFeature1 = FindFeature(textBox109.Text);
                            measure_Tool.EllipseSetValueL = Convert.ToDouble(textBox106.Text);//长度设定值
                            measure_Tool.EllipsePositiveValueL = Convert.ToDouble(textBox107.Text);//长度正公差
                            measure_Tool.EllipseNegativeValueL = Convert.ToDouble(textBox108.Text);//长度负公差
                            if (CompensationValueL == true)
                            {
                                measure_Tool.EllipseCompensationValueLeftL = Convert.ToDouble(textBox105.Text);//长度补偿
                            }
                            if (CompensationValueR == true)
                            {
                                measure_Tool.EllipseCompensationValueRightL = Convert.ToDouble(textBox105.Text);
                            }
                            measure_Tool.EllipseMaxValueL = measure_Tool.EllipseSetValueL + measure_Tool.EllipsePositiveValueL; //长度上限
                            measure_Tool.EllipseMinValueL = measure_Tool.EllipseSetValueL - measure_Tool.EllipseNegativeValueL;//长度下限

                            measure_Tool.EllipseSetValueW = Convert.ToDouble(textBox112.Text);//宽设定值
                            measure_Tool.EllipsePositiveValueW = Convert.ToDouble(textBox111.Text);//宽正公差
                            measure_Tool.EllipseNegativeValueW = Convert.ToDouble(textBox110.Text);//宽负公差
                            if (CompensationValueL == true)
                            {
                                measure_Tool.EllipseCompensationValueLeftW = Convert.ToDouble(textBox113.Text);//宽补偿
                            }
                            if (CompensationValueR == true)
                            {
                                measure_Tool.EllipseCompensationValueRightW = Convert.ToDouble(textBox113.Text);
                            }
                            measure_Tool.EllipseMaxValueW = measure_Tool.EllipseSetValueW + measure_Tool.EllipsePositiveValueW;//宽上限
                            measure_Tool.EllipseMinValueW = measure_Tool.EllipseSetValueW - measure_Tool.EllipseNegativeValueW;//宽下限
                            productList.Product_list[Now_Product_ID].MeasureList.Add(measure_Tool);
                            listBox2.Items.Add(str);
                            break;

                    }

                }
                catch (Exception error)
                {

                }
            }
            if (comboBox3.SelectedIndex == 6)
            {
                str = "测量Pin孔";
                measure_Tool.PinName = str;
                measure_Tool.PinSetValueL = Convert.ToDouble(textBox98.Text);
                measure_Tool.PinPositiveValueL = Convert.ToDouble(textBox47.Text);
                measure_Tool.PinNegativeValueL = Convert.ToDouble(textBox48.Text);

                measure_Tool.PinSetValueW = Convert.ToDouble(textBox100.Text);
                measure_Tool.PinPositiveValueW = Convert.ToDouble(textBox51.Text);
                measure_Tool.PinNegativeValueW = Convert.ToDouble(textBox53.Text);

                measure_Tool.PinSetValueX = Convert.ToDouble(textBox101.Text);
                measure_Tool.PinPositiveValueX = Convert.ToDouble(textBox50.Text);
                measure_Tool.PinNegativeValueX = Convert.ToDouble(textBox49.Text);

                measure_Tool.PinSetValueY = Convert.ToDouble(textBox103.Text);
                measure_Tool.PinPositiveValueY = Convert.ToDouble(textBox52.Text);
                measure_Tool.PinNegativeValueY = Convert.ToDouble(textBox54.Text);
                if (CompensationValueL == true)
                {
                    measure_Tool.PinCompensationValueLeftL = Convert.ToDouble(textBox97.Text);
                    measure_Tool.PinMaxValueL = measure_Tool.PinSetValueL + measure_Tool.PinCompensationValueLeftL + measure_Tool.PinPositiveValueL;
                    measure_Tool.PinMinValueL = measure_Tool.PinSetValueL + measure_Tool.PinCompensationValueLeftL - measure_Tool.PinNegativeValueL;

                    measure_Tool.PinCompensationValueLeftW = Convert.ToDouble(textBox99.Text);
                    measure_Tool.PinMaxValueW = measure_Tool.PinSetValueW + measure_Tool.PinCompensationValueLeftW + measure_Tool.PinPositiveValueW;
                    measure_Tool.PinMinValueW = measure_Tool.PinSetValueW + measure_Tool.PinCompensationValueLeftW - measure_Tool.PinPositiveValueW;

                    measure_Tool.PinCompensationValueLeftX = Convert.ToDouble(textBox102.Text);
                    measure_Tool.PinMaxCircleX = measure_Tool.PinSetValueX + measure_Tool.PinCompensationValueLeftX + measure_Tool.PinPositiveValueX;
                    measure_Tool.PinMinCircleX = measure_Tool.PinSetValueX + measure_Tool.PinCompensationValueLeftX - measure_Tool.PinNegativeValueX;

                    measure_Tool.PinCompensationValueLeftY = Convert.ToDouble(textBox104.Text);
                    measure_Tool.PinMaxCircleY = measure_Tool.PinSetValueY + measure_Tool.PinCompensationValueLeftY + measure_Tool.PinPositiveValueY;
                    measure_Tool.PinMinCircleY = measure_Tool.PinSetValueY + measure_Tool.PinCompensationValueLeftY - measure_Tool.PinNegativeValueY;
                }
                if (CompensationValueR == true)
                {
                    measure_Tool.PinCompensationValueRightL = Convert.ToDouble(textBox97.Text);
                    measure_Tool.PinMaxValueL = measure_Tool.PinSetValueL + measure_Tool.PinCompensationValueRightL + measure_Tool.PinPositiveValueL;
                    measure_Tool.PinMinValueL = measure_Tool.PinSetValueL + measure_Tool.PinCompensationValueRightL - measure_Tool.PinNegativeValueL;

                    measure_Tool.PinCompensationValueRightW = Convert.ToDouble(textBox99.Text);
                    measure_Tool.PinMaxValueW = measure_Tool.PinSetValueW + measure_Tool.PinCompensationValueRightW + measure_Tool.PinPositiveValueW;
                    measure_Tool.PinMinValueW = measure_Tool.PinSetValueW + measure_Tool.PinCompensationValueRightW - measure_Tool.PinPositiveValueW;

                    measure_Tool.PinCompensationValueRightX = Convert.ToDouble(textBox102.Text);
                    measure_Tool.PinMaxCircleX = measure_Tool.PinSetValueX + measure_Tool.PinCompensationValueRightX + measure_Tool.PinPositiveValueX;
                    measure_Tool.PinMinCircleX = measure_Tool.PinSetValueX + measure_Tool.PinCompensationValueRightX - measure_Tool.PinNegativeValueX;

                    measure_Tool.PinCompensationValueRightY = Convert.ToDouble(textBox104.Text);
                    measure_Tool.PinMaxCircleY = measure_Tool.PinSetValueY + measure_Tool.PinCompensationValueRightY + measure_Tool.PinPositiveValueY;
                    measure_Tool.PinMinCircleY = measure_Tool.PinSetValueY + measure_Tool.PinCompensationValueRightY - measure_Tool.PinNegativeValueY;
                }
                measure_Tool.Measure_Style = Measure_Style.PinCheck;
                productList.Product_list[Now_Product_ID].MeasureList.Add(measure_Tool);
                listBox2.Items.Add(str);
            }
        }

        private void button27_Click(object sender, EventArgs e)
        {
            if (listBox2.SelectedIndex > -1)
            {
                productList.Product_list[Now_Product_ID].MeasureList.RemoveAt(listBox2.SelectedIndex);
                listBox2.Items.RemoveAt(listBox2.SelectedIndex);
            }
        }

        private void button28_Click(object sender, EventArgs e)
        {
            if (listBox2.SelectedIndex > -1)
            {
                bool Is_Model1 = File.Exists(productList.Product_list[Now_Product_ID].StandraModel_Path1);
                bool Is_Model2 = File.Exists(productList.Product_list[Now_Product_ID].StandraModel_Path2);
                bool Is_ModelRegion1 = File.Exists(productList.Product_list[Now_Product_ID].ModelRegion_Path1);
                bool Is_ModelRegion2 = File.Exists(productList.Product_list[Now_Product_ID].ModelRegion_Path2);
                string temp_code = "";
                if (Is_Model1 == true && Is_Model2 == true)
                {
                    HTuple scale = 4;
                    HTuple Row = 0;
                    HTuple Column = 0;
                    HTuple Angle = 0;
                    Measure measure = new Measure(manualImage_width, manualImage_Height);
                    HOperatorSet.ReadShapeModel(productList.Product_list[Now_Product_ID].StandraModel_Path1, out HTuple ModelID1);
                    HOperatorSet.ReadShapeModel(productList.Product_list[Now_Product_ID].StandraModel_Path2, out HTuple ModelID2);
                    if (Is_ModelRegion1 && Is_ModelRegion2)
                    {
                        HOperatorSet.ReadRegion(out HObject modelRegion1, productList.Product_list[Now_Product_ID].ModelRegion_Path1);
                        HOperatorSet.AreaCenter(modelRegion1, out HTuple area1, out HTuple row1, out HTuple column1);
                        HOperatorSet.HomMat2dIdentity(out HTuple homMat2D1);
                        HOperatorSet.HomMat2dScale(homMat2D1, scale, scale, row1, column1, out HTuple homMat2dScale1);
                        HOperatorSet.AffineTransRegion(modelRegion1, out HObject regionAffineTrans1, homMat2dScale1, "nearest_neighbor");
                        HOperatorSet.ReduceDomain(manualImage, regionAffineTrans1, out HObject image1);

                        HOperatorSet.ReadRegion(out HObject modelRegion2, productList.Product_list[Now_Product_ID].ModelRegion_Path2);
                        HOperatorSet.AreaCenter(modelRegion2, out HTuple area2, out HTuple row2, out HTuple column2);
                        HOperatorSet.HomMat2dIdentity(out HTuple homMat2D2);
                        HOperatorSet.HomMat2dScale(homMat2D2, scale, scale, row2, column2, out HTuple homMat2dScale2);
                        HOperatorSet.AffineTransRegion(modelRegion2, out HObject regionAffineTrans2, homMat2dScale2, "nearest_neighbor");
                        HOperatorSet.ReduceDomain(manualImage, regionAffineTrans2, out HObject image2);

                        //HOperatorSet.DispObj(regionAffineTrans1, hSmartWindowControl1.HalconWindow);
                        //HOperatorSet.DispObj(regionAffineTrans2, hSmartWindowControl1.HalconWindow);

                        Algorithm.Create_Stanrad_Point(image1, image2, out HObject RegionLine, out HObject Circle_Region, ModelID1, ModelID2, out Row, out Column, out Angle);

                    }
                    else
                        Algorithm.Create_Stanrad_Point(manualImage, out HObject RegionLine, out HObject Circle_Region, ModelID1, ModelID2, out Row, out Column, out Angle);
                    double Rotation_Center = Angle.D - productList.Product_list[Now_Product_ID].Standard_Angle;
                    if (Rotation_Center > 3) Rotation_Center = Rotation_Center - 3.1415;
                    if (Rotation_Center < -3) Rotation_Center = Rotation_Center + 3.1415;

                    HOperatorSet.VectorAngleToRigid(productList.Product_list[Now_Product_ID].Standard_Row, productList.Product_list[Now_Product_ID].Standard_Column, 0, Row, Column, Rotation_Center, out HTuple HomMat2DTranslate);
                    //获取所有区域结果
                    List<LineAndRecangelResult> lineAndRecangelResults = new List<LineAndRecangelResult>();
                    string path = "";
                    for (int i = 0; i < productList.Product_list[Now_Product_ID].FeaturesList.Count; i++)
                    {
                        path = productList.Product_list[Now_Product_ID].FeaturesList[i].Region_Path;
                        if (File.Exists(path))
                        {
                            measure.GetResult(hSmartWindowControl5, productList.Product_list[Now_Product_ID].FeaturesList[i], manualImage, HomMat2DTranslate, path, lineAndRecangelResults);
                        }
                    }
                    //计算轴线
                    Feature feature1 = productList.Product_list[Now_Product_ID].FeaturesList.Find(x => x.Name.Contains("基准轴") && x.Name.Contains(","));
                    Feature feature2 = productList.Product_list[Now_Product_ID].FeaturesList.Find(x => x.Name.Contains("基准轴") && !x.Name.Contains(","));
                    if (feature1 != null && feature2 != null)
                    {
                        string pointName1 = feature1.Name.Split('_')[1].Split(',')[0];
                        string pointName2 = feature1.Name.Split('_')[1].Split(',')[1];
                        double startRow1 = lineAndRecangelResults.Find(x => x.name == pointName1).centerRow;
                        double startCol1 = lineAndRecangelResults.Find(x => x.name == pointName1).centerCol;
                        double endRow1 = lineAndRecangelResults.Find(x => x.name == pointName2).centerRow;
                        double endCol1 = lineAndRecangelResults.Find(x => x.name == pointName2).centerCol;
                        lineAndRecangelResults.Add(new LineAndRecangelResult() { name = feature1.Name, startRow = startRow1, startCol = startCol1, endRow = endRow1, endCol = endCol1 });
                        HOperatorSet.GenRegionLine(out HObject regionline1, startRow1, startCol1, endRow1, endCol1);
                        HOperatorSet.DispObj(regionline1, hSmartWindowControl5.HalconWindow);
                        //投影轴线
                        string pointName3 = feature2.Name.Split('_')[1];
                        double startRow3 = lineAndRecangelResults.Find(x => x.name == pointName3).centerRow;
                        double startCol3 = lineAndRecangelResults.Find(x => x.name == pointName3).centerCol;
                        HOperatorSet.ProjectionPl(startRow3, startCol3, startRow1, startCol1, endRow1, endCol1, out HTuple rowProj, out HTuple colProj);
                        lineAndRecangelResults.Add(new LineAndRecangelResult() { name = feature2.Name, startRow = startRow3, startCol = startCol3, endRow = rowProj, endCol = colProj });
                    
                    HOperatorSet.DispObj(regionline1, hSmartWindowControl5.HalconWindow);
                    HOperatorSet.GenRegionLine(out HObject regionline2, startRow3, startCol3, rowProj, colProj);
                    }
                    //计算点构线
                    Feature feature3 = productList.Product_list[Now_Product_ID].FeaturesList.Find(x => x.Name.Contains("点构线") && x.Name.Contains(","));
                    if (feature3!= null )
                    {
                        //点构线
                        string pointName4 = feature3.Name.Split('_')[1].Split(',')[0];
                        string pointName5 = feature3.Name.Split('_')[1].Split(',')[1];
                        double startRow = lineAndRecangelResults.Find(x => x.name == pointName4).centerRow;
                        double startCol = lineAndRecangelResults.Find(x => x.name == pointName4).centerCol;
                        double endRow = lineAndRecangelResults.Find(x => x.name == pointName5).centerRow;
                        double endCol = lineAndRecangelResults.Find(x => x.name == pointName5).centerCol;
                        lineAndRecangelResults.Add(new LineAndRecangelResult() { name = feature3.Name, startRow = startRow, startCol = startCol, endRow = endRow, endCol = endCol });
                        HOperatorSet.GenRegionLine(out HObject regionline, startRow, startCol, endRow, endCol);
                        HOperatorSet.DispObj(regionline, hSmartWindowControl5.HalconWindow);
                    }
                    if (productList.Product_list[Now_Product_ID].MeasureList.Count > 0 && listBox2.SelectedIndex > -1)
                    {

                        if (productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].Measure_Tool_Run(hSmartWindowControl5, manualImage, manualImage_width, manualImage_Height, HomMat2DTranslate, Calibration_CameraLeft, ref temp_code, configfil.Left_Scaled, lineAndRecangelResults,"Left").Distance!=0)
                        {

                        }
                        else
                            MessageBox.Show("尺寸测量失败");

                    }
                }
            }
        }

        private void button32_Click(object sender, EventArgs e)
        {
            if (listBox2.SelectedIndex > -1)
            {
                switch (productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].Measure_Style)
                {
                    case Measure_Style.Point_To_Point:
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].MeasureFeature1.Name = textBox27.Text;
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].MeasureFeature2.Name = textBox28.Text;
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].SetValue = Convert.ToDouble(textBox87.Text.Trim());
                        if (CompensationValueL == true)
                        {
                            productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].CompensationValueLeft = Convert.ToDouble(textBox88.Text.Trim());
                        }
                        if (CompensationValueR == true)
                        {
                            productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].CompensationValueRight = Convert.ToDouble(textBox88.Text.Trim());
                        }

                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PositiveValue = Convert.ToDouble(textBox29.Text.Trim());
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].NegativeValue = Convert.ToDouble(textBox30.Text.Trim());
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].MaxValue = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].SetValue + productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PositiveValue;
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].MinValue = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].SetValue - productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].NegativeValue;
                        MessageBox.Show("修改成功");
                        break;
                    case Measure_Style.Point_To_Line:
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].MeasureFeature1.Name = textBox31.Text;
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].MeasureFeature2.Name = textBox32.Text;
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].SetValue = Convert.ToDouble(textBox90.Text.Trim());
                        if (CompensationValueL == true)
                        {
                            productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].CompensationValueLeft = Convert.ToDouble(textBox89.Text.Trim());
                        }
                        if (CompensationValueR == true)
                        {
                            productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].CompensationValueRight = Convert.ToDouble(textBox89.Text.Trim());
                        }
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PositiveValue = Convert.ToDouble(textBox33.Text.Trim());
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].NegativeValue = Convert.ToDouble(textBox34.Text.Trim());
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].MaxValue = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].SetValue + productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PositiveValue;
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].MinValue = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].SetValue - productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].NegativeValue;
                        MessageBox.Show("修改成功");
                        break;
                    case Measure_Style.Line_To_Line:
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].MeasureFeature1.Name = textBox35.Text;
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].MeasureFeature2.Name = textBox36.Text;
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].MeasureFeature3.Name = textBox39.Text;
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].SetValue = Convert.ToDouble(textBox92.Text.Trim());
                        if (CompensationValueL == true)
                        {
                            productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].CompensationValueLeft = Convert.ToDouble(textBox91.Text.Trim());
                        }
                        if (CompensationValueR == true)
                        {
                            productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].CompensationValueRight = Convert.ToDouble(textBox91.Text.Trim());
                        }
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PositiveValue = Convert.ToDouble(textBox37.Text.Trim());
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].NegativeValue = Convert.ToDouble(textBox38.Text.Trim());
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].MaxValue = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].SetValue + productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PositiveValue;
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].MinValue = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].SetValue - productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].NegativeValue;
                        MessageBox.Show("修改成功");
                        break;
                    case Measure_Style.Screw:
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].MeasureFeature1.Name = textBox40.Text;
                        MessageBox.Show("修改成功");
                        break;
                    case Measure_Style.ReadCode:
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].MeasureFeature1.Name = textBox41.Text;
                        MessageBox.Show("修改成功");
                        break;
                    case Measure_Style.Circle_Measure:
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].MeasureFeature1.Name = textBox42.Text;
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].SetValue = Convert.ToDouble(textBox94.Text.Trim());
                        if (CompensationValueL == true)
                        {
                            productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].CompensationValueLeft = Convert.ToDouble(textBox93.Text.Trim());
                        }
                        if (CompensationValueR == true)
                        {
                            productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].CompensationValueRight = Convert.ToDouble(textBox93.Text.Trim());
                        }
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PositiveValue = Convert.ToDouble(textBox43.Text.Trim());
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].NegativeValue = Convert.ToDouble(textBox44.Text.Trim());
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].MaxValue = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].SetValue + productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PositiveValue;
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].MinValue = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].SetValue - productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].NegativeValue;
                        MessageBox.Show("修改成功");
                        break;
                    case Measure_Style.PinCheck:
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinSetValueL = Convert.ToDouble(textBox98.Text.Trim());
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinPositiveValueL = Convert.ToDouble(textBox47.Text.Trim());
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinNegativeValueL = Convert.ToDouble(textBox48.Text.Trim());
 
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinSetValueW = Convert.ToDouble(textBox100.Text.Trim());
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinPositiveValueW = Convert.ToDouble(textBox51.Text.Trim());
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinNegativeValueW = Convert.ToDouble(textBox53.Text.Trim());

                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinSetValueX = Convert.ToDouble(textBox101.Text.Trim());
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinPositiveValueX = Convert.ToDouble(textBox50.Text.Trim());
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinNegativeValueX = Convert.ToDouble(textBox49.Text.Trim());

                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinSetValueY = Convert.ToDouble(textBox103.Text.Trim());
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinPositiveValueY = Convert.ToDouble(textBox52.Text.Trim());
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinNegativeValueY = Convert.ToDouble(textBox54.Text.Trim());
                        if (CompensationValueL == true)
                        {
                            productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinCompensationValueLeftL = Convert.ToDouble(textBox97.Text);
                            productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinMaxValueL = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinSetValueL  + productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinPositiveValueL;
                            productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinMinValueL = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinSetValueL  - productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinNegativeValueL;

                            productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinCompensationValueLeftW = Convert.ToDouble(textBox99.Text);
                            productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinMaxValueW = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinSetValueW  + productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinPositiveValueW;
                            productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinMinValueW = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinSetValueW  - productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinNegativeValueW;

                            productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinCompensationValueLeftX = Convert.ToDouble(textBox102.Text);
                            productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinMaxCircleX = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinSetValueX + productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinPositiveValueX;
                            productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinMinCircleX = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinSetValueX  - productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinNegativeValueX;

                            productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinCompensationValueLeftY = Convert.ToDouble(textBox104.Text);
                            productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinMaxCircleY = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinSetValueY + productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinPositiveValueY;
                            productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinMinCircleY = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinSetValueY  - productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinNegativeValueY;
                        }
                        if (CompensationValueR == true)
                        {
                            productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinCompensationValueRightL = Convert.ToDouble(textBox97.Text);
                            productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinMaxValueL = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinSetValueL  + productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinPositiveValueL;
                            productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinMinValueL = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinSetValueL  - productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinNegativeValueL;

                            productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinCompensationValueRightW = Convert.ToDouble(textBox99.Text);
                            productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinMaxValueW = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinSetValueW  + productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinPositiveValueW;
                            productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinMinValueW = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinSetValueW  - productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinNegativeValueW;

                            productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinCompensationValueRightX = Convert.ToDouble(textBox102.Text);
                            productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinMaxCircleX = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinSetValueX  + productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinPositiveValueX;
                            productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinMinCircleX = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinSetValueX  - productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinNegativeValueX;

                            productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinCompensationValueRightY = Convert.ToDouble(textBox104.Text);
                            productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinMaxCircleY = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinSetValueY + productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinPositiveValueY;
                            productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinMinCircleY = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinSetValueY  - productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinNegativeValueY;
                        }
                        MessageBox.Show("修改成功");
                        break;
                    case Measure_Style.Projection:
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].MeasureFeature1.Name = textBox81.Text;
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].MeasureFeature2.Name = textBox83.Text;
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].MeasureFeature3.Name = textBox82.Text;
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].SetValue = Convert.ToDouble(textBox96.Text.Trim());
                        if (CompensationValueL == true)
                        {
                            productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].CompensationValueLeft = Convert.ToDouble(textBox95.Text.Trim());
                        }
                        if (CompensationValueR == true)
                        {
                            productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].CompensationValueRight = Convert.ToDouble(textBox95.Text.Trim());
                        }
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PositiveValue = Convert.ToDouble(textBox84.Text.Trim());
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].NegativeValue = Convert.ToDouble(textBox85.Text.Trim());
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].MaxValue = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].SetValue + productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PositiveValue;
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].MinValue = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].SetValue - productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].NegativeValue;
                        break;
                     case Measure_Style.Ellipse:
                         productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].MeasureFeature1.Name = textBox109.Text;
                         productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].EllipseSetValueL = Convert.ToDouble(textBox106.Text.Trim());//长度设定值
                         productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].EllipsePositiveValueL = Convert.ToDouble(textBox107.Text.Trim());//长度正公差
                         productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].EllipseNegativeValueL = Convert.ToDouble(textBox108.Text.Trim());//长度负公差
                        if (CompensationValueL == true)
                        {
                            productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].EllipseCompensationValueLeftL = Convert.ToDouble(textBox105.Text.Trim());//长度补偿
                        }
                        if (CompensationValueR == true)
                        {
                            productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].EllipseCompensationValueRightL = Convert.ToDouble(textBox105.Text.Trim());//长度补偿
                        }
                        productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].EllipseMaxValueL =  productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].EllipseSetValueL +  productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].EllipsePositiveValueL; //长度上限
                         productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].EllipseMinValueL =  productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].EllipseSetValueL -  productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].EllipseNegativeValueL;//长度下限

                         productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].EllipseSetValueW = Convert.ToDouble(textBox112.Text.Trim());//宽设定值
                         productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].EllipsePositiveValueW = Convert.ToDouble(textBox111.Text.Trim());//宽正公差
                         productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].EllipseNegativeValueW = Convert.ToDouble(textBox110.Text.Trim());//宽负公差
                        if (CompensationValueL == true)
                        {
                            productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].EllipseCompensationValueLeftW = Convert.ToDouble(textBox113.Text.Trim());//宽补偿
                        }
                        if (CompensationValueR == true)
                        {
                            productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].EllipseCompensationValueRightW = Convert.ToDouble(textBox113.Text.Trim());//宽补偿
                        }
                         productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].EllipseMaxValueW =  productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].EllipseSetValueW +  productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].EllipsePositiveValueW;//宽上限
                         productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].EllipseMinValueW =  productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].EllipseSetValueW -  productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].EllipseNegativeValueW;//宽下限
                        MessageBox.Show("修改成功");
                        break;
                    default:
                        break;


                }
            }
        }

        private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listBox2.SelectedIndex > -1)
            {
                try
                {
                    string Pinname = listBox2.SelectedItem.ToString();
                    if (Pinname == "测量Pin孔")
                    {
                        tabControl2.SelectedIndex = 6;
                        if (CompensationValueL == true)
                        {
                            textBox97.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinCompensationValueLeftL.ToString();
                            textBox99.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinCompensationValueLeftW.ToString();
                            textBox102.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinCompensationValueLeftX.ToString();
                            textBox104.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinCompensationValueLeftY.ToString();
                        }
                        if (CompensationValueR == true)
                        {
                            textBox97.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinCompensationValueRightL.ToString();
                            textBox99.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinCompensationValueRightW.ToString();
                            textBox102.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinCompensationValueRightX.ToString();
                            textBox104.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinCompensationValueRightY.ToString();
                        }
                        textBox98.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinSetValueL.ToString();
                        textBox47.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinPositiveValueL.ToString();
                        textBox48.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinNegativeValueL.ToString();

                        textBox100.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinSetValueW.ToString();
                        textBox51.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinPositiveValueW.ToString();
                        textBox53.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinNegativeValueW.ToString();

                        textBox101.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinSetValueX.ToString();
                        textBox50.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinPositiveValueX.ToString();
                        textBox49.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinNegativeValueX.ToString();

                        textBox103.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinSetValueY.ToString();
                        textBox52.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinPositiveValueY.ToString();
                        textBox54.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PinNegativeValueY.ToString();
                        return;
                    }
                    switch (productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].Measure_Style)
                    {
                        case Measure_Style.Point_To_Point:
                            tabControl2.SelectedIndex = 0;
                            textBox27.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].MeasureFeature1.Name;
                            textBox28.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].MeasureFeature2.Name;
                            textBox87.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].SetValue.ToString();
                            if (CompensationValueL == true)
                            {
                                textBox88.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].CompensationValueLeft.ToString();
                            }
                            if (CompensationValueR == true)
                            {
                                textBox88.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].CompensationValueRight.ToString();
                            }
                            textBox29.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PositiveValue.ToString();
                            textBox30.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].NegativeValue.ToString();
                            break;
                        case Measure_Style.Point_To_Line:
                            tabControl2.SelectedIndex = 1;
                            textBox31.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].MeasureFeature1.Name;
                            textBox32.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].MeasureFeature2.Name;
                            textBox90.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].SetValue.ToString();
                            if (CompensationValueL == true)
                            {
                                textBox89.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].CompensationValueLeft.ToString();
                            }
                            if (CompensationValueR == true)
                            {
                                textBox89.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].CompensationValueRight.ToString();
                            }
                            textBox33.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PositiveValue.ToString();
                            textBox34.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].NegativeValue.ToString();
                            break;
                        case Measure_Style.Line_To_Line:
                            tabControl2.SelectedIndex = 2;
                            textBox35.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].MeasureFeature1.Name;
                            textBox36.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].MeasureFeature2.Name;
                            textBox39.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].MeasureFeature3.Name;
                            textBox92.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].SetValue.ToString();
                            if (CompensationValueL == true)
                            {
                                textBox91.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].CompensationValueLeft.ToString();
                            }
                            if (CompensationValueR == true)
                            {
                                textBox91.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].CompensationValueRight.ToString();
                            }
                            textBox37.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PositiveValue.ToString();
                            textBox38.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].NegativeValue.ToString();
                            break;
                        case Measure_Style.Circle_Measure:
                            tabControl2.SelectedIndex = 5;
                            textBox42.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].MeasureFeature1.Name;
                            textBox94.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].SetValue.ToString();
                            if (CompensationValueL == true)
                            {
                                textBox93.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].CompensationValueLeft.ToString();
                            }
                            if (CompensationValueR == true)
                            {
                                textBox93.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].CompensationValueRight.ToString();
                            }
                            textBox43.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PositiveValue.ToString();
                            textBox44.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].NegativeValue.ToString();
                            break;
                        case Measure_Style.Projection:
                            tabControl2.SelectedIndex = 7;
                            textBox81.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].MeasureFeature1.Name;
                            textBox83.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].MeasureFeature2.Name;
                            textBox82.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].MeasureFeature3.Name;
                            textBox96.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].SetValue.ToString();
                            if (CompensationValueL == true)
                            {
                                textBox95.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].CompensationValueLeft.ToString();
                            }
                            if (CompensationValueR == true)
                            {
                                textBox95.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].CompensationValueRight.ToString();
                            }
                            textBox84.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].PositiveValue.ToString();
                            textBox85.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].NegativeValue.ToString();
                            break;
                        case Measure_Style.Ellipse:
                            tabControl2.SelectedIndex = 8;
                            textBox109.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].MeasureFeature1.Name;
                            textBox106.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].EllipseSetValueL.ToString();
                            textBox107.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].EllipsePositiveValueL.ToString();
                            textBox108.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].EllipseNegativeValueL.ToString();
                            if (CompensationValueL == true)
                            {
                                textBox105.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].EllipseCompensationValueLeftL.ToString();
                            }
                            if (CompensationValueR == true)
                            {
                                textBox105.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].EllipseCompensationValueRightL.ToString();
                            }
                            textBox112.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].EllipseSetValueW.ToString();
                            textBox111.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].EllipsePositiveValueW.ToString();
                            textBox110.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].EllipseNegativeValueW.ToString();
                            if (CompensationValueL == true)
                            {
                                textBox113.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].EllipseCompensationValueLeftW.ToString();
                            }
                            if (CompensationValueR == true)
                            {
                                textBox113.Text = productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].EllipseCompensationValueRightW.ToString();
                            }
                            break;

                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }


            }
        }

        private void button34_Click(object sender, EventArgs e)
        {
            if (listBox1.SelectedIndex > -1)
            {
                if (productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.Circle || productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.SemiCircle)
                {
                    textBox31.Text = listBox1.SelectedItem.ToString();
                }
                else
                {
                    MessageBox.Show("选择的特征类型错误");
                }

            }
        }

        private void button33_Click(object sender, EventArgs e)
        {
            if (listBox1.SelectedIndex > -1)
            {
                if (productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.Line || productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.LineXY || productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.LineRC)
                {
                    textBox32.Text = listBox1.SelectedItem.ToString();
                }
                else
                {
                    MessageBox.Show("选择的特征类型错误");
                }

            }
        }

        private void button36_Click(object sender, EventArgs e)
        {
            if (listBox1.SelectedIndex > -1)
            {
                if (productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.Line || productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.LineXY || productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.LineRC)
                {
                    textBox35.Text = listBox1.SelectedItem.ToString();
                }
                else
                {
                    MessageBox.Show("选择的特征类型错误");
                }

            }
        }

        private void button35_Click(object sender, EventArgs e)
        {
            if (listBox1.SelectedIndex > -1)
            {
                if (productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.Line || productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.LineXY || productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.LineRC)
                {
                    textBox36.Text = listBox1.SelectedItem.ToString();
                }
                else
                {
                    MessageBox.Show("选择的特征类型错误");
                }

            }
        }

        private void button37_Click(object sender, EventArgs e)
        {
            if (listBox1.SelectedIndex > -1)
            {
                if (productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.Line || productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.LineXY || productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.LineRC)
                {
                    textBox39.Text = listBox1.SelectedItem.ToString();
                }
                else
                {
                    MessageBox.Show("选择的特征类型错误");
                }

            }
        }

        private void button38_Click(object sender, EventArgs e)
        {
            if (listBox1.SelectedIndex > -1)
            {
                if (productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.Circle)
                {
                    textBox40.Text = listBox1.SelectedItem.ToString();
                }
                else
                {
                    MessageBox.Show("选择的特征类型错误");
                }

            }
        }

        private void button39_Click(object sender, EventArgs e)
        {
            if (listBox1.SelectedIndex > -1)
            {
                if (productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.ReadCode)
                {
                    textBox41.Text = listBox1.SelectedItem.ToString();
                }
                else
                {
                    MessageBox.Show("选择的特征类型错误");
                }

            }
        }

        private void button14_Click(object sender, EventArgs e)
        {
            if (DraROI != null)
            {
                if (DraROI.ID != 0)
                {
                    string[] str = new string[] { "row1", "column1", "row2", "column2" };
                    try
                    {
                        HTuple hTuple = DraROI.GetDrawingObjectParams(str);

                        HOperatorSet.GenRectangle1(out HObject ROI, hTuple.LArr[0], hTuple.LArr[1], hTuple.LArr[2], hTuple.LArr[3]);
                        Algorithm.Add_Measure_SemiCircle(manualImage, ROI, out HObject Ho_Corcle, out HTuple Row, out HTuple Column);
                        HOperatorSet.SetColor(hSmartWindowControl5.HalconWindow, "red");
                        DraROI.ClearDrawingObject();
                        HOperatorSet.DispRegion(Ho_Corcle, hSmartWindowControl5.HalconWindow);
                        Feature feature = new Feature();
                        feature._Style = Feature_Style.SemiCircle;
                        //feature.Name = "半圆区域" + productList.Product_list[Now_Product_ID].FeaturesList.Count;
                        feature.Name = GetName("半圆区域", productList.Product_list[Now_Product_ID].FeaturesList.Count);
                        //feature.Region_Path = Directory.GetCurrentDirectory() + "\\Product\\" + productList.Product_list[Now_Product_ID].ProductName + "\\Region" + productList.Product_list[Now_Product_ID].FeaturesList.Count + ".hobj";
                        feature.Region_Path = Directory.GetCurrentDirectory() + "\\Product\\" + productList.Product_list[Now_Product_ID].ProductName + "\\" + feature.Name + ".hobj";
                        feature.Region_Path.Replace("半圆区域", "SemiCircle");
                        HOperatorSet.WriteRegion(ROI, feature.Region_Path);
                        productList.Product_list[Now_Product_ID].FeaturesList.Add(feature);
                        listBox1.Items.Add(feature.Name);

                    }
                    catch (Exception error)
                    {
                        MessageBox.Show(error.Message);
                    }
                    DraROI.Dispose();
                }
            }
        }

        private void checkBox4_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox4.Checked == true)
            {
                Measure_record = true;

            }
            else
            {
                //Measure_record = false;
            }
        }

        private void button15_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("是否确定将特征清空", "提示", MessageBoxButtons.YesNo);
            if (result == DialogResult.Yes)
            {
                productList.Product_list[Now_Product_ID].FeaturesList.Clear();
                productList.Product_list[Now_Product_ID].HikStandraModel_Path = " ";
                productList.Product_list[Now_Product_ID].HikProductName = " ";
                productList.Product_list[Now_Product_ID].Pinchek = false;
                listBox1.Items.Clear();
                listBox8.Items.Clear();
                MessageBox.Show("成功");
            }
        }

        private void button16_Click_1(object sender, EventArgs e)
        {
            if (listBox1.SelectedIndex > -1)
            {
                if (productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.Circle)
                {
                    textBox42.Text = listBox1.SelectedItem.ToString();
                }
                else
                {
                    MessageBox.Show("选择的特征类型错误");
                }

            }
        }

        private void button17_Click(object sender, EventArgs e)
        {
            try
            {
                configfil.Left_Scaled = Convert.ToDouble(textBox45.Text);
                configfil.Right_Scaled = Convert.ToDouble(textBox46.Text);
                MessageBox.Show("设置参数成功");
            }
            catch
            {
                MessageBox.Show("设置参数异常");
            }
        }

        private void button18_Click(object sender, EventArgs e)
        {
            if (comboBox2.SelectedIndex > -1)
            {
                productList.Product_Now = productList.Product_list[comboBox2.SelectedIndex].ProductName;
                label54.Text = productList.Product_list[comboBox2.SelectedIndex].ProductName;
                Now_Product_ID = Find_Now_ID(productList);
                DialogResult result = MessageBox.Show("是否确定删除产品"+comboBox2.SelectedItem.ToString(), "提示", MessageBoxButtons.YesNoCancel);
                if (result == DialogResult.Yes)
                {
                    productList.Product_list[Now_Product_ID].FeaturesList.Clear();
                    listBox1.Items.Clear();
                    productList.Product_list[Now_Product_ID].HikStandraModel_Path = " ";
                    productList.Product_list[Now_Product_ID].HikProductName = " ";
                    productList.Product_list[Now_Product_ID].Pinchek = false;
                    listBox8.Items.Clear();
                    productList.Product_list[Now_Product_ID].MeasureList.Clear();
                    listBox2.Items.Clear();
                    productList.Product_list.RemoveAt(comboBox2.SelectedIndex);
                    comboBox2.Items.RemoveAt(comboBox2.SelectedIndex);
                    MessageBox.Show("删除成功！");
                }
            }
        }

        private void button40_Click(object sender, EventArgs e)
        {
            if (listBox2.SelectedIndex > -1)
            {
                bool Is_Model1 = File.Exists(productList.Product_list[Now_Product_ID].StandraModel_Path1);
                bool Is_Model2 = File.Exists(productList.Product_list[Now_Product_ID].StandraModel_Path2);
                bool Is_ModelRegion1 = File.Exists(productList.Product_list[Now_Product_ID].ModelRegion_Path1);
                bool Is_ModelRegion2 = File.Exists(productList.Product_list[Now_Product_ID].ModelRegion_Path2);
                string temp_code = "";
                if (Is_Model1 == true && Is_Model2 == true)
                {
                    HTuple scale = 4;
                    HTuple Row = 0;
                    HTuple Column = 0;
                    HTuple Angle = 0;
                    Measure measure = new Measure(manualImage_width, manualImage_Height);
                    HOperatorSet.ReadShapeModel(productList.Product_list[Now_Product_ID].StandraModel_Path1, out HTuple ModelID1);
                    HOperatorSet.ReadShapeModel(productList.Product_list[Now_Product_ID].StandraModel_Path2, out HTuple ModelID2);
                    if (Is_ModelRegion1 && Is_ModelRegion2)
                    {
                        HOperatorSet.ReadRegion(out HObject modelRegion1, productList.Product_list[Now_Product_ID].ModelRegion_Path1);
                        HOperatorSet.AreaCenter(modelRegion1, out HTuple area1, out HTuple row1, out HTuple column1);
                        HOperatorSet.HomMat2dIdentity(out HTuple homMat2D1);
                        HOperatorSet.HomMat2dScale(homMat2D1, scale, scale, row1, column1, out HTuple homMat2dScale1);
                        HOperatorSet.AffineTransRegion(modelRegion1, out HObject regionAffineTrans1, homMat2dScale1, "nearest_neighbor");
                        HOperatorSet.ReduceDomain(manualImage, regionAffineTrans1, out HObject image1);

                        HOperatorSet.ReadRegion(out HObject modelRegion2, productList.Product_list[Now_Product_ID].ModelRegion_Path2);
                        HOperatorSet.AreaCenter(modelRegion2, out HTuple area2, out HTuple row2, out HTuple column2);
                        HOperatorSet.HomMat2dIdentity(out HTuple homMat2D2);
                        HOperatorSet.HomMat2dScale(homMat2D2, scale, scale, row2, column2, out HTuple homMat2dScale2);
                        HOperatorSet.AffineTransRegion(modelRegion2, out HObject regionAffineTrans2, homMat2dScale2, "nearest_neighbor");
                        HOperatorSet.ReduceDomain(manualImage, regionAffineTrans2, out HObject image2);

                        //HOperatorSet.DispObj(regionAffineTrans1, hSmartWindowControl1.HalconWindow);
                        //HOperatorSet.DispObj(regionAffineTrans2, hSmartWindowControl1.HalconWindow);

                        Algorithm.Create_Stanrad_Point(image1, image2, out HObject RegionLine, out HObject Circle_Region, ModelID1, ModelID2, out Row, out Column, out Angle);

                    }
                    else
                        Algorithm.Create_Stanrad_Point(manualImage, out HObject RegionLine, out HObject Circle_Region, ModelID1, ModelID2, out  Row, out  Column, out  Angle);
                    double Rotation_Center = Angle.D - productList.Product_list[Now_Product_ID].Standard_Angle;

                    if (Rotation_Center > 3) Rotation_Center = Rotation_Center - 3.1415;
                    if (Rotation_Center < -3) Rotation_Center = Rotation_Center + 3.1415;
                    HOperatorSet.VectorAngleToRigid(productList.Product_list[Now_Product_ID].Standard_Row, productList.Product_list[Now_Product_ID].Standard_Column, 0, Row, Column, Rotation_Center, out HTuple HomMat2DTranslate);
                    //获取所有区域结果
                    List<LineAndRecangelResult> lineAndRecangelResults = new List<LineAndRecangelResult>();
                    string path = "";
                    for (int i = 0; i < productList.Product_list[Now_Product_ID].FeaturesList.Count; i++)
                    {
                        path = productList.Product_list[Now_Product_ID].FeaturesList[i].Region_Path;
                        if (File.Exists(path))
                        {
                            measure.GetResult(hSmartWindowControl5, productList.Product_list[Now_Product_ID].FeaturesList[i], manualImage, HomMat2DTranslate, path, lineAndRecangelResults);
                        }
                    }
                    //计算轴线
                    Feature feature1 = productList.Product_list[Now_Product_ID].FeaturesList.Find(x => x.Name.Contains("基准轴") && x.Name.Contains(","));
                    Feature feature2 = productList.Product_list[Now_Product_ID].FeaturesList.Find(x => x.Name.Contains("基准轴") && !x.Name.Contains(","));
                    if (feature1 != null && feature2 != null)
                    {
                        string pointName1 = feature1.Name.Split('_')[1].Split(',')[0];
                        string pointName2 = feature1.Name.Split('_')[1].Split(',')[1];
                        double startRow1 = lineAndRecangelResults.Find(x => x.name == pointName1).centerRow;
                        double startCol1 = lineAndRecangelResults.Find(x => x.name == pointName1).centerCol;
                        double endRow1 = lineAndRecangelResults.Find(x => x.name == pointName2).centerRow;
                        double endCol1 = lineAndRecangelResults.Find(x => x.name == pointName2).centerCol;
                        lineAndRecangelResults.Add(new LineAndRecangelResult() { name = feature1.Name, startRow = startRow1, startCol = startCol1, endRow = endRow1, endCol = endCol1 });
                        HOperatorSet.GenRegionLine(out HObject regionline1, startRow1, startCol1, endRow1, endCol1);
                        HOperatorSet.DispObj(regionline1, hSmartWindowControl5.HalconWindow);
                        //投影轴线
                        string pointName3 = feature2.Name.Split('_')[1];
                        double startRow3 = lineAndRecangelResults.Find(x => x.name == pointName3).centerRow;
                        double startCol3 = lineAndRecangelResults.Find(x => x.name == pointName3).centerCol;
                        HOperatorSet.ProjectionPl(startRow3, startCol3, startRow1, startCol1, endRow1, endCol1, out HTuple rowProj, out HTuple colProj);
                        lineAndRecangelResults.Add(new LineAndRecangelResult() { name = feature2.Name, startRow = startRow3, startCol = startCol3, endRow = rowProj, endCol = colProj });
                        HOperatorSet.DispObj(regionline1, hSmartWindowControl5.HalconWindow);
                        HOperatorSet.GenRegionLine(out HObject regionline2, startRow3, startCol3, rowProj, colProj);
                    }
                    //计算点构线
                    Feature feature3 = productList.Product_list[Now_Product_ID].FeaturesList.Find(x => x.Name.Contains("点构线") && x.Name.Contains(","));
                    if (feature3 != null)
                    {
                        //点构线
                        string pointName4 = feature3.Name.Split('_')[1].Split(',')[0];
                        string pointName5 = feature3.Name.Split('_')[1].Split(',')[1];
                        double startRow = lineAndRecangelResults.Find(x => x.name == pointName4).centerRow;
                        double startCol = lineAndRecangelResults.Find(x => x.name == pointName4).centerCol;
                        double endRow = lineAndRecangelResults.Find(x => x.name == pointName5).centerRow;
                        double endCol = lineAndRecangelResults.Find(x => x.name == pointName5).centerCol;
                        lineAndRecangelResults.Add(new LineAndRecangelResult() { name = feature3.Name, startRow = startRow, startCol = startCol, endRow = endRow, endCol = endCol });
                        HOperatorSet.GenRegionLine(out HObject regionline, startRow, startCol, endRow, endCol);
                        HOperatorSet.DispObj(regionline, hSmartWindowControl5.HalconWindow);
                    }
                    if (productList.Product_list[Now_Product_ID].MeasureList.Count > 0 && listBox2.SelectedIndex > -1)
                    {
                        if (productList.Product_list[Now_Product_ID].MeasureList[listBox2.SelectedIndex].Measure_Tool_Run(hSmartWindowControl5, manualImage, manualImage_width, manualImage_Height, HomMat2DTranslate, Calibration_CameraRight, ref temp_code, configfil.Right_Scaled, lineAndRecangelResults,"Right").Distance!=0)
                        {

                        }
                        else
                            MessageBox.Show("尺寸测量失败");
                        
                    }
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (DraROI != null)
            {
                string[] str1 = new string[] { "row1", "column1", "row2", "column2" };
                try
                {
                    HTuple hTuple = DraROI.GetDrawingObjectParams(str1);
                    HOperatorSet.GenRectangle1(out HObject ROI, hTuple.LArr[0], hTuple.LArr[1], hTuple.LArr[2], hTuple.LArr[3]);
                    if (Directory.Exists(Directory.GetCurrentDirectory() + "\\Product\\" + productList.Product_list[Now_Product_ID].ProductName + "\\HikCamera\\") == false)
                    {
                        Directory.CreateDirectory(Directory.GetCurrentDirectory() + "\\Product\\" + productList.Product_list[Now_Product_ID].ProductName + "\\HikCamera\\");
                    }
                    string HikCameraRegionPath = Directory.GetCurrentDirectory() + "\\Product\\" + productList.Product_list[Now_Product_ID].ProductName + "\\HikCamera\\" + "HikStanrd_Model.hobj";
                    productList.Product_list[Now_Product_ID].HikStandraModel_Path = HikCameraRegionPath;
                    productList.Product_list[Now_Product_ID].HikProductName = "PIN区域";
                    productList.Product_list[Now_Product_ID].Pinchek = true;
                    HOperatorSet.WriteRegion(ROI, HikCameraRegionPath);
                    listBox8.Items.Add(productList.Product_list[Now_Product_ID].HikProductName);

                }
                catch (Exception error)
                {
                    MessageBox.Show(error.Message);
                }
                MessageBox.Show("创建成功");
                return;
            }
            else
            {
                MessageBox.Show("未选择ROI工具");
            }
        }

        private void button41_Click(object sender, EventArgs e)
        {
            try
            {
                HOperatorSet.ReadRegion(out HObject HikRegion, productList.Product_list[Now_Product_ID].HikStandraModel_Path);
                HOperatorSet.ReduceDomain(manualImage, HikRegion, out HObject ImageReduced);
                HOperatorSet.Threshold(ImageReduced, out HObject Region, 200, 255);
                HOperatorSet.Connection(Region, out HObject ConnectedRegions);
                HOperatorSet.SelectShape(ConnectedRegions, out HObject SelectedRegions, "width", "and", 50, 100);
                HOperatorSet.SelectShape(SelectedRegions, out HObject SelectedRegions2, "height", "and", 50, 100);
                HOperatorSet.SelectShape(SelectedRegions2, out HObject SelectedRegions1, "area", "and", 1800, 99999);
                HOperatorSet.CountObj(SelectedRegions1, out HTuple Number);
                if ((int)(new HTuple(Number.TupleGreaterEqual(2))) != 0)
                {
                    HOperatorSet.SelectObj(SelectedRegions1, out HObject ObjectSelected, 1);
                    HOperatorSet.SelectObj(SelectedRegions1, out HObject ObjectSelected1, 2);
                    //获取外圆中心坐标
                    HOperatorSet.AreaCenter(ObjectSelected, out HTuple Areawy, out HTuple Rowwy, out HTuple Columnwy);
                    HOperatorSet.AreaCenter(ObjectSelected1, out HTuple Areawy1, out HTuple Rowwy1, out HTuple Columnwy1);
                    //外圆区域抠出图像
                    HOperatorSet.SmallestRectangle1(SelectedRegions1, out HTuple Row1, out HTuple Column1, out HTuple Row2, out HTuple Column2);
                    HOperatorSet.GenRectangle1(out HObject Rectangle, Row1, Column1, Row2, Column2);
                    HOperatorSet.CountObj(Rectangle, out HTuple Number1);
                    HOperatorSet.SelectObj(Rectangle, out HObject ObjectSelected2, 1);
                    HOperatorSet.SelectObj(Rectangle, out HObject ObjectSelected21, 2);
                    HOperatorSet.ReduceDomain(ImageReduced, ObjectSelected2, out HObject ImageReduced1);
                    HOperatorSet.ReduceDomain(ImageReduced, ObjectSelected21, out HObject ImageReduced2);
                    HOperatorSet.SetColor(hSmartWindowControl5.HalconWindow, "red");
                    HOperatorSet.DispRegion(ObjectSelected1, hSmartWindowControl5.HalconWindow);
                    HOperatorSet.DispRegion(ObjectSelected, hSmartWindowControl5.HalconWindow);
                    ObjectSelected.Dispose();
                    ObjectSelected1.Dispose();
                    Areawy.Dispose(); Rowwy.Dispose(); Columnwy.Dispose();
                    Areawy1.Dispose(); Rowwy1.Dispose(); Columnwy1.Dispose();
                    Row1.Dispose(); Column1.Dispose(); Row2.Dispose(); Column2.Dispose();
                    Rectangle.Dispose();
                    Number1.Dispose();
                    ObjectSelected2.Dispose();
                    ObjectSelected21.Dispose();
                    ImageReduced1.Dispose();
                    ImageReduced2.Dispose();
                }
                else
                {
                    MessageBox.Show("未找到匹配图像");
                }

                ImageReduced.Dispose();
                Region.Dispose();
                ConnectedRegions.Dispose();
                SelectedRegions.Dispose();
                SelectedRegions2.Dispose();
                SelectedRegions1.Dispose();
                Number.Dispose();
            }
            catch (Exception error)
            {
                MessageBox.Show("验证失败!" + error.Message);
            }
            return;

        }

        private void button42_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("是否确定将测量列表清空", "提示", MessageBoxButtons.YesNo);
            if (result == DialogResult.Yes)
            {
                if (Now_Product_ID > -1)
                {
                    productList.Product_list[Now_Product_ID].MeasureList.Clear();
                    listBox2.Items.Clear();
                }
            }
        }

        private void button43_Click(object sender, EventArgs e)
        {
            if (DraROI != null)
            {
                string[] str = new string[] { "row1", "column1", "row2", "column2" };
                try
                {
                    HTuple hTuple = DraROI.GetDrawingObjectParams(str);
                    HOperatorSet.GenRectangle1(out ModelRegion, hTuple.LArr[0], hTuple.LArr[1], hTuple.LArr[2], hTuple.LArr[3]);
                    DraROI.ClearDrawingObject();
                    try
                    {
                        if (Directory.Exists(Directory.GetCurrentDirectory() + "\\Product\\" + productList.Product_list[Now_Product_ID].ProductName) == false)
                        {
                            Directory.CreateDirectory(Directory.GetCurrentDirectory() + "\\Product\\" + productList.Product_list[Now_Product_ID].ProductName);
                        }
                        HOperatorSet.WriteRegion(ModelRegion, Directory.GetCurrentDirectory() + "\\Product\\" + productList.Product_list[Now_Product_ID].ProductName + "\\ModelRegion1.hobj");
                        productList.Product_list[Now_Product_ID].ModelRegion_Path1 = Directory.GetCurrentDirectory() + "\\Product\\" + productList.Product_list[Now_Product_ID].ProductName + "\\ModelRegion1.hobj";
                        Algorithm.Create_Stanrd_model(manualImage, ModelRegion, Directory.GetCurrentDirectory() + "\\Product\\" + productList.Product_list[Now_Product_ID].ProductName + "\\Stanrd_Model1.hobj", out HTuple Row, out HTuple Column);
                        productList.Product_list[Now_Product_ID].StandraModel_Path1 = Directory.GetCurrentDirectory() + "\\Product\\" + productList.Product_list[Now_Product_ID].ProductName + "\\Stanrd_Model1.hobj";

                        HOperatorSet.ReadShapeModel(productList.Product_list[Now_Product_ID].StandraModel_Path1, out HTuple ModeID);
                        HOperatorSet.FindScaledShapeModel(manualImage, ModeID, (new HTuple(-30)).TupleRad(), (new HTuple(30)).TupleRad(), 0.9, 1.1, 0.2, 1, 0.5, "least_squares", 0, 0.9, out HTuple Row1, out HTuple Column1, out HTuple Angle1, out HTuple Scale1, out HTuple Score1);
                        HOperatorSet.GetShapeModelContours(out HObject ho_ModelContours, ModeID, 1);
                        if (Score1.Length > 0)
                        {
                            HOperatorSet.HomMat2dIdentity(out HTuple HomMat2DIdentity);
                            HOperatorSet.HomMat2dTranslate(HomMat2DIdentity, Row1, Column1, out HTuple HomMat2DTranslate);
                            HOperatorSet.HomMat2dRotateLocal(HomMat2DTranslate, Angle1, out HTuple HomMat2DRotate);
                            HOperatorSet.AffineTransContourXld(ho_ModelContours, out HObject ContoursAffineTrans, HomMat2DRotate);
                            HOperatorSet.SetColor(hSmartWindowControl5.HalconWindow, "red");
                            HOperatorSet.DispXld(ContoursAffineTrans, hSmartWindowControl5.HalconWindow);
                        }
                        else
                        {
                            MessageBox.Show("没有找到对应的基准点");
                        }

                    }
                    catch
                    {
                        MessageBox.Show("模型创建失败");
                    }

                }
                catch (Exception error)
                {
                    MessageBox.Show(error.Message);
                    return;
                }
                MessageBox.Show("创建成功");
            }
            else
            {
                MessageBox.Show("未选择ROI工具");
            }
        }

        private void button44_Click(object sender, EventArgs e)
        {
            if (DraROI != null)
            {
                string[] str = new string[] { "row1", "column1", "row2", "column2" };
                try
                {
                    HTuple hTuple = DraROI.GetDrawingObjectParams(str);
                    HOperatorSet.GenRectangle1(out ModelRegion, hTuple.LArr[0], hTuple.LArr[1], hTuple.LArr[2], hTuple.LArr[3]);
                    DraROI.ClearDrawingObject();
                    try
                    {
                        if (Directory.Exists(Directory.GetCurrentDirectory() + "\\Product\\" + productList.Product_list[Now_Product_ID].ProductName) == false)
                        {
                            Directory.CreateDirectory(Directory.GetCurrentDirectory() + "\\Product\\" + productList.Product_list[Now_Product_ID].ProductName);
                        }
                        HOperatorSet.WriteRegion(ModelRegion, Directory.GetCurrentDirectory() + "\\Product\\" + productList.Product_list[Now_Product_ID].ProductName + "\\ModelRegion2.hobj");
                        productList.Product_list[Now_Product_ID].ModelRegion_Path2 = Directory.GetCurrentDirectory() + "\\Product\\" + productList.Product_list[Now_Product_ID].ProductName + "\\ModelRegion2.hobj";

                        Algorithm.Create_Stanrd_model(manualImage, ModelRegion, Directory.GetCurrentDirectory() + "\\Product\\" + productList.Product_list[Now_Product_ID].ProductName + "\\Stanrd_Model2.hobj", out HTuple Row, out HTuple Column);
                        productList.Product_list[Now_Product_ID].StandraModel_Path2 = Directory.GetCurrentDirectory() + "\\Product\\" + productList.Product_list[Now_Product_ID].ProductName + "\\Stanrd_Model2.hobj";

                        HOperatorSet.ReadShapeModel(productList.Product_list[Now_Product_ID].StandraModel_Path2, out HTuple ModeID);
                        HOperatorSet.FindScaledShapeModel(manualImage, ModeID, (new HTuple(-30)).TupleRad(), (new HTuple(30)).TupleRad(), 0.9, 1.1, 0.2, 1, 0.5, "least_squares", 0, 0.9, out HTuple Row1, out HTuple Column1, out HTuple Angle1, out HTuple Scale1, out HTuple Score1);
                        HOperatorSet.GetShapeModelContours(out HObject ho_ModelContours, ModeID, 1);
                        if (Score1.Length > 0)
                        {
                            HOperatorSet.HomMat2dIdentity(out HTuple HomMat2DIdentity);
                            HOperatorSet.HomMat2dTranslate(HomMat2DIdentity, Row1, Column1, out HTuple HomMat2DTranslate);
                            HOperatorSet.HomMat2dRotateLocal(HomMat2DTranslate, Angle1, out HTuple HomMat2DRotate);
                            HOperatorSet.AffineTransContourXld(ho_ModelContours, out HObject ContoursAffineTrans, HomMat2DRotate);
                            HOperatorSet.SetColor(hSmartWindowControl5.HalconWindow, "red");
                            HOperatorSet.DispXld(ContoursAffineTrans, hSmartWindowControl5.HalconWindow);
                        }
                        else
                        {
                            MessageBox.Show("没有找到对应的基准点");
                        }

                    }
                    catch
                    {
                        MessageBox.Show("模型创建失败");
                    }

                }
                catch (Exception error)
                {
                    MessageBox.Show(error.Message);
                    return;
                }
                MessageBox.Show("创建成功");
            }
            else
            {
                MessageBox.Show("未选择ROI工具");
            }
        }

        private void button45_Click(object sender, EventArgs e)
        {
            try
            {
                PinCheck pincheck = new PinCheck();
                if (productList.Product_list[Now_Product_ID].HikStandraModel_Path != null)
                {
                    HOperatorSet.ReadRegion(out HObject Region, productList.Product_list[Now_Product_ID].HikStandraModel_Path);
                    for (int i = 0; i < productList.Product_list[Now_Product_ID].MeasureList.Count; i++)
                    {
                        if (productList.Product_list[Now_Product_ID].MeasureList[i].PinName != "")
                        {
                            pincheck = productList.Product_list[Now_Product_ID].MeasureList[i].MeasurePin(hSmartWindowControl5, manualImage, Region, HikLeftCameraParam, HikLeftPose,"Left");
                        }
                    }
                    if (pincheck.TestReult == false)
                    {
                       
                    }
                }
                else
                {
                    MessageBox.Show("未找到匹配图像路径");
                }

            }
            catch (Exception error)
            {
                MessageBox.Show("错误!" + error.Message);
            }
        }

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Enter)
                {
                    tool.SaveConfigFile(configfil);
                    tool.SaveProductFile(productList);
                    MessageBox.Show("保存成功");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("保存异常！");
            }

        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox2.Checked == true)
            {
                productList.Product_list[Now_Product_ID].Pinchek = true;
            }
            else
            {
                productList.Product_list[Now_Product_ID].Pinchek = false;
            }
        }

        private void label69_Click(object sender, EventArgs e)
        {

        }

        private void label71_Click(object sender, EventArgs e)
        {

        }

        private void label73_Click(object sender, EventArgs e)
        {

        }

        private void label75_Click(object sender, EventArgs e)
        {

        }

        private void label77_Click(object sender, EventArgs e)
        {

        }

        private void button49_Click(object sender, EventArgs e)
        {
            if (PLC_Connection == true)
            {
                try
                {
                    textBox55.Text = (PLC.ReadInt32("R154").Content / 1000).ToString();
                    textBox57.Text = (PLC.ReadInt32("R156").Content / 1000).ToString();
                    textBox59.Text = (PLC.ReadInt32("R158").Content / 1000).ToString();
                    //PIN孔位置
                    textBox61.Text = (PLC.ReadInt32("R160").Content / 1000).ToString();
                    textBox63.Text = (PLC.ReadInt32("R162").Content / 1000).ToString();

                    textBox56.Text = (PLC.ReadInt32("R104").Content / 1000).ToString();
                    textBox58.Text = (PLC.ReadInt32("R106").Content / 1000).ToString();
                    textBox60.Text = (PLC.ReadInt32("R108").Content / 1000).ToString();
                    textBox62.Text = (PLC.ReadInt32("R110").Content / 1000).ToString();
                    textBox64.Text = (PLC.ReadInt32("R112").Content / 1000).ToString();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }

        private void button50_Click(object sender, EventArgs e)
        {
            if (PLC_Connection == true)
            {
                try
                {
                    textBox65.Text = (PLC.ReadInt32("R254").Content / 1000).ToString();
                    textBox66.Text = (PLC.ReadInt32("R256").Content / 1000).ToString();
                    textBox68.Text = (PLC.ReadInt32("R258").Content / 1000).ToString();
                    //PIN孔位置
                    textBox69.Text = (PLC.ReadInt32("R260").Content / 1000).ToString();
                    textBox71.Text = (PLC.ReadInt32("R262").Content / 1000).ToString();

                    textBox67.Text = (PLC.ReadInt32("R204").Content / 1000).ToString();
                    textBox70.Text = (PLC.ReadInt32("R206").Content / 1000).ToString();
                    textBox72.Text = (PLC.ReadInt32("R208").Content / 1000).ToString();
                    textBox73.Text = (PLC.ReadInt32("R210").Content / 1000).ToString();
                    textBox74.Text = (PLC.ReadInt32("R212").Content / 1000).ToString();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }

        private void button47_Click(object sender, EventArgs e)
        {
            if (PLC_Connection == true)
            {
                try
                {
                    PLC.Write("R104", Convert.ToInt32(textBox56.Text) * 1000);
                    PLC.Write("R106", Convert.ToInt32(textBox58.Text) * 1000);
                    PLC.Write("R108", Convert.ToInt32(textBox60.Text) * 1000);
                    PLC.Write("R110", Convert.ToInt32(textBox62.Text) * 1000);
                    PLC.Write("R112", Convert.ToInt32(textBox64.Text) * 1000);
                    productList.Product_list[Now_Product_ID].LeftPinchekPos = (PLC.ReadInt32("R160").Content / 1000).ToString();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }

        private void button48_Click(object sender, EventArgs e)
        {
            if (PLC_Connection == true)
            {
                try
                {
                    PLC.Write("R204", Convert.ToInt32(textBox67.Text) * 1000);
                    PLC.Write("R206", Convert.ToInt32(textBox70.Text) * 1000);
                    PLC.Write("R208", Convert.ToInt32(textBox72.Text) * 1000);
                    PLC.Write("R210", Convert.ToInt32(textBox73.Text) * 1000);
                    PLC.Write("R212", Convert.ToInt32(textBox74.Text) * 1000);
                    productList.Product_list[Now_Product_ID].RightPinchekPos = (PLC.ReadInt32("R260").Content / 1000).ToString();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }

        private void button51_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Title = "导入模板图片";
            openFileDialog.ShowDialog();
            if (openFileDialog.FileName != "")
            {
                HOperatorSet.ReadImage(out CalibrationImage, openFileDialog.FileName);
                HOperatorSet.GetImageSize(CalibrationImage, out HTuple width, out HTuple height);
                CalibrationImage_width = width;
                CalibrationImage_Height = height;
                HOperatorSet.SetPart(hSmartWindowControl6.HalconWindow, 0, 0, height - 1, width - 1);
                //HOperatorSet.ScaleImage(manualImage, out  manualImage, 10, 20);
                HOperatorSet.DispObj(CalibrationImage, hSmartWindowControl6.HalconWindow);
                hSmartWindowControl6.SetFullImagePart();
            }
        }

        private void button53_Click(object sender, EventArgs e)
        {
            if (DraROICalibration != null) DraROICalibration.ClearDrawingObject();
            DraROICalibration = HDrawingObject.CreateDrawingObject(HDrawingObject.HDrawingObjectType.LINE, 1000, 1000, 2000, 1000);
            DraROICalibration.SetDrawingObjectParams("color", "green");
            hSmartWindowControl6.HalconWindow.AttachDrawingObjectToWindow(DraROICalibration);
        }

        private void button52_Click(object sender, EventArgs e)
        {
            if (DraROICalibration != null) DraROICalibration.ClearDrawingObject();
        }

        private void button54_Click(object sender, EventArgs e)
        {
            if (DraROICalibration != null)
            {
                if (DraROICalibration.ID != 0)
                {
                    string[] str = new string[] { "row1", "column1", "row2", "column2" };
                    HTuple hTuple = DraROICalibration.GetDrawingObjectParams(str);
                    //Algorithm.LIN(manualImage, hTuple.LArr[0], hTuple.LArr[1], hTuple.LArr[2], hTuple.LArr[3], 100, 10, out HTuple A1, out HTuple B1, out HTuple A2, out HTuple B2);
                    Algorithm.GetLine(CalibrationImage, 100, 10, hTuple.LArr[0], hTuple.LArr[1], hTuple.LArr[2], hTuple.LArr[3], out HTuple A1, out HTuple B1, out HTuple A2, out HTuple B2);
                    HOperatorSet.GenRegionLine(out HObject RetangleRegion, A1, B1, A2, B2);
                    DraROICalibration.ClearDrawingObject();
                    HOperatorSet.SetColor(hSmartWindowControl6.HalconWindow, "red");
                    HOperatorSet.DispRegion(RetangleRegion, hSmartWindowControl6.HalconWindow);
                    Feature feature = new Feature();
                    feature._Style = Feature_Style.Line;
                    feature.Name = "直线" + productList.Product_list[Now_Product_ID].CalibrationLineList.Count;
                    feature.LineStartPoint.Row = A1.D;
                    feature.LineStartPoint.Column = B1.D;
                    feature.LineEndPoint.Row = A2.D;
                    feature.LineEndPoint.Column = B2.D;
                    productList.Product_list[Now_Product_ID].CalibrationLineList.Add(feature);
                    listBox3.Items.Add(feature.Name);
                    DraROICalibration.Dispose();

                }
            }
        }

        private void button61_Click(object sender, EventArgs e)
        {
            if (listBox3.SelectedIndex > -1)
            {
                productList.Product_list[Now_Product_ID].CalibrationLineList.RemoveAt(listBox3.SelectedIndex);
                listBox3.Items.RemoveAt(listBox3.SelectedIndex);
                MessageBox.Show("删除成功");
            }
        }

        private void button62_Click(object sender, EventArgs e)
        {
            productList.Product_list[Now_Product_ID].CalibrationLineList.Clear();
            listBox3.Items.Clear();
            MessageBox.Show("成功");
        }

        private void listBox3_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listBox3.SelectedIndex > -1)
            {
                HOperatorSet.GenRegionLine(out HObject H_Line_Region, productList.Product_list[Now_Product_ID].CalibrationLineList[listBox3.SelectedIndex].LineStartPoint.Row, productList.Product_list[Now_Product_ID].CalibrationLineList[listBox3.SelectedIndex].LineStartPoint.Column, productList.Product_list[Now_Product_ID].CalibrationLineList[listBox3.SelectedIndex].LineEndPoint.Row, productList.Product_list[Now_Product_ID].CalibrationLineList[listBox3.SelectedIndex].LineEndPoint.Column);
                HOperatorSet.SetColor(hSmartWindowControl6.HalconWindow, "red");
                HOperatorSet.DispRegion(H_Line_Region, hSmartWindowControl6.HalconWindow);
                HOperatorSet.DispText(hSmartWindowControl6.HalconWindow, productList.Product_list[Now_Product_ID].CalibrationLineList[listBox3.SelectedIndex].Name, "image", (productList.Product_list[Now_Product_ID].CalibrationLineList[listBox3.SelectedIndex].LineStartPoint.Row + productList.Product_list[Now_Product_ID].CalibrationLineList[listBox3.SelectedIndex].LineEndPoint.Row) / 2, (productList.Product_list[Now_Product_ID].CalibrationLineList[listBox3.SelectedIndex].LineStartPoint.Column + productList.Product_list[Now_Product_ID].CalibrationLineList[listBox3.SelectedIndex].LineEndPoint.Column) / 2, "red", "box", "false");
            }
        }

        private void button57_Click(object sender, EventArgs e)
        {
            if (listBox3.SelectedIndex > -1)
            {
                textBox75.Text = listBox3.SelectedItem.ToString();
                CalibrationLInenumber1 = listBox3.SelectedIndex;
            }

        }

        private void button56_Click(object sender, EventArgs e)
        {
            if (listBox3.SelectedIndex > -1)
            {
                textBox77.Text = listBox3.SelectedItem.ToString();
                CalibrationLInenumber2 = listBox3.SelectedIndex;
            }
        }

        private void button55_Click(object sender, EventArgs e)
        {
            if (textBox75.Text != "" && textBox77.Text != "")
            {
                Measure_Tool measure_Tool = new Measure_Tool();
                Calibration calibration = new Calibration();
                double line1StartRow, line1StartColumn, Line1EndRow, Line1EndColumn;
                double line2StartRow, line2StartColumn, Line2EndRow, Line2EndColumn;

                line1StartRow = productList.Product_list[Now_Product_ID].CalibrationLineList[CalibrationLInenumber1].LineStartPoint.Row;
                line1StartColumn = productList.Product_list[Now_Product_ID].CalibrationLineList[CalibrationLInenumber1].LineStartPoint.Column;
                Line1EndRow = productList.Product_list[Now_Product_ID].CalibrationLineList[CalibrationLInenumber1].LineEndPoint.Row;
                Line1EndColumn = productList.Product_list[Now_Product_ID].CalibrationLineList[CalibrationLInenumber1].LineEndPoint.Column;

                line2StartRow = productList.Product_list[Now_Product_ID].CalibrationLineList[CalibrationLInenumber2].LineStartPoint.Row;
                line2StartColumn = productList.Product_list[Now_Product_ID].CalibrationLineList[CalibrationLInenumber2].LineStartPoint.Column;
                Line2EndRow = productList.Product_list[Now_Product_ID].CalibrationLineList[CalibrationLInenumber2].LineEndPoint.Row;
                Line2EndColumn = productList.Product_list[Now_Product_ID].CalibrationLineList[CalibrationLInenumber2].LineEndPoint.Column;
                calibration = measure_Tool.CalibrationLine(hSmartWindowControl6, line1StartRow, line1StartColumn, Line1EndRow, Line1EndColumn, line2StartRow, line2StartColumn, Line2EndRow, Line2EndColumn);
                textBox78.Text = calibration.Row.ToString("0.00");
                textBox79.Text = calibration.Column.ToString("0.00");
            }

        }

        private void button58_Click(object sender, EventArgs e)
        {
            if (textBox78.Text != "" && textBox79.Text != "")
            {
                listBox4.Items.Add(textBox78.Text);
                listBox5.Items.Add(textBox79.Text);
            }

        }

        private void button59_Click(object sender, EventArgs e)
        {
            if (textBox76.Text != "" && textBox80.Text != "")
            {
                listBox7.Items.Add(textBox76.Text);
                listBox6.Items.Add(textBox80.Text);
            }
        }

        private void button60_Click(object sender, EventArgs e)
        {
            if (listBox7.Items != null && listBox6.Items != null)
            {
                HTuple Px = new HTuple();
                HTuple Py = new HTuple();
                HTuple Qx = new HTuple();
                HTuple Qy = new HTuple();
                Px[0] = Convert.ToDouble(listBox4.Items[0]);
                Px[1] = Convert.ToDouble(listBox4.Items[1]);
                Px[2] = Convert.ToDouble(listBox4.Items[2]);
                Px[3] = Convert.ToDouble(listBox4.Items[3]);

                Py[0] = Convert.ToDouble(listBox5.Items[0]);
                Py[1] = Convert.ToDouble(listBox5.Items[1]);
                Py[2] = Convert.ToDouble(listBox5.Items[2]);
                Py[3] = Convert.ToDouble(listBox5.Items[3]);

                Qx[0] = Convert.ToDouble(listBox7.Items[0]);
                Qx[1] = Convert.ToDouble(listBox7.Items[1]);
                Qx[2] = Convert.ToDouble(listBox7.Items[2]);
                Qx[3] = Convert.ToDouble(listBox7.Items[3]);

                Qy[0] = Convert.ToDouble(listBox6.Items[0]);
                Qy[1] = Convert.ToDouble(listBox6.Items[1]);
                Qy[2] = Convert.ToDouble(listBox6.Items[2]);
                Qy[3] = Convert.ToDouble(listBox6.Items[3]);

                HOperatorSet.VectorToHomMat2d(Px, Py, Qx, Qy, out HTuple HomMat2D);
                if (checkBox3.Checked == true)
                {
                    HOperatorSet.WriteTuple(HomMat2D, Directory.GetCurrentDirectory() + "//Config//Camera_Left");
                    HOperatorSet.ReadTuple(Directory.GetCurrentDirectory() + "//Config//Camera_Left", out Calibration_CameraLeft);
                    MessageBox.Show("生成左工位标定文件成功");
                }
                if (checkBox5.Checked == true)
                {
                    HOperatorSet.WriteTuple(HomMat2D, Directory.GetCurrentDirectory() + "//Config//Camera_Right");
                    HOperatorSet.ReadTuple(Directory.GetCurrentDirectory() + "//Config//Camera_Right", out Calibration_CameraRight);
                    MessageBox.Show("生成右工位标定文件成功");
                }

                Py.Dispose();
                Px.Dispose();
                Qx.Dispose();
                Qy.Dispose();
                HomMat2D.Dispose();
            }
        }

        private void checkBox3_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox3.Checked == true)
            {
                checkBox5.Checked = false;
            }

        }

        private void checkBox5_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox5.Checked == true)
            {
                checkBox3.Checked = false;
            }
        }

        private void button63_Click(object sender, EventArgs e)
        {
            HTuple Column, Row, Qx, Qy;
            if (listBox4.SelectedIndex > -1 && listBox5.SelectedIndex > -1)
            {
                if (checkBox3.Checked == true)
                {
                    try
                    {
                        Column = Convert.ToDouble(listBox5.SelectedItem);
                        Row = Convert.ToDouble(listBox4.SelectedItem);
                        HOperatorSet.AffineTransPoint2d(Calibration_CameraLeft, Row, Column, out Qx, out Qy);
                        label101.Text = Qy.D.ToString("0.00");
                        label100.Text = Qx.D.ToString("0.00");
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }

                }
                if (checkBox5.Checked == true)
                {
                    try
                    {
                        Column = Convert.ToDouble(listBox5.SelectedItem);
                        Row = Convert.ToDouble(listBox4.SelectedItem);
                        HOperatorSet.AffineTransPoint2d(Calibration_CameraRight, Row, Column, out Qx, out Qy);
                        label101.Text = Qy.D.ToString("0.00");
                        label100.Text = Qx.D.ToString("0.00");
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }

                }


            }
            else { MessageBox.Show("请选择需要验证的图像坐标"); }
        }

        private void button64_Click(object sender, EventArgs e)
        {
            listBox4.Items.Clear();
            listBox5.Items.Clear();
        }

        private void button65_Click(object sender, EventArgs e)
        {
            listBox7.Items.Clear();
            listBox6.Items.Clear();
        }

        private void button68_Click(object sender, EventArgs e)
        {
            if (listBox1.SelectedIndex > -1)
            {
                if (productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.Line|| productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.LineXY|| productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.LineRC)
                {
                    textBox81.Text = listBox1.SelectedItem.ToString();
                }
                else
                {
                    MessageBox.Show("选择的特征类型错误");
                }

            }
        }

        private void button67_Click(object sender, EventArgs e)
        {
            if (listBox1.SelectedIndex > -1)
            {
                if (productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.Circle || productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.SemiCircle|| productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.ellipse)
                {
                    textBox83.Text = listBox1.SelectedItem.ToString();
                }
                else
                {
                    MessageBox.Show("选择的特征类型错误");
                }

            }
        }

        private void button66_Click(object sender, EventArgs e)
        {
            if (listBox1.SelectedIndex > -1)
            {
                if (productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.Circle || productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.SemiCircle|| productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.ellipse)
                {
                    textBox82.Text = listBox1.SelectedItem.ToString();
                }
                else
                {
                    MessageBox.Show("选择的特征类型错误");
                }

            }
        }

        private void button69_Click(object sender, EventArgs e)
        {
            configfil.MesSavePath = tool.OpenSaveImagePath();
            if (configfil.MesSavePath != "")
            {
                DialogResult result = MessageBox.Show("是否将测试数据存储在路径下" + configfil.MesSavePath, "提示", MessageBoxButtons.YesNoCancel);
                if (result == DialogResult.Yes)
                {
                    tool.SaveConfigFile(configfil);
                    MessageBox.Show("图片存储在路径已更新 " + configfil.MesSavePath, "提示");
                    textBox86.Text = configfil.MesSavePath;
                }
            }
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (comboBox1.SelectedIndex > -1)
                {
                    if (comboBox1.SelectedItem.ToString() == "海康左" + configfil.HikLeftCameraSeria)
                    {
                        textBox1.Text = configfil.HikLeftCameraExposureTime.ToString();
                    }
                    if (comboBox1.SelectedItem.ToString() == "海康右" + configfil.HikRightCameraSeria)
                    {
                        textBox1.Text = configfil.HikRightCameraExposureTime.ToString();
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }

        private void textBox19_TextChanged(object sender, EventArgs e)
        {

        }

        private void button71_Click(object sender, EventArgs e)
        {
            LineTriggerCamera lineTriggerCamera = new LineTriggerCamera();
            string configFileName = lineTriggerCamera.GetOption();
            if (configFileName != null)
            {
                DialogResult result = MessageBox.Show("是否需要保存配置文件路径" + configFileName, "提示", MessageBoxButtons.YesNoCancel);
                if (result == DialogResult.Yes)
                {
                    configfil.RightCameraConfigepath = configFileName;
                    textBox20.Text = configfil.RightCameraConfigepath;
                    tool.SaveConfigFile(configfil);
                }
            }
        }

        private void button70_Click(object sender, EventArgs e)
        {
            LineTriggerCamera lineTriggerCamera = new LineTriggerCamera();
            string configFileName = lineTriggerCamera.GetOption();
            if (configFileName != null)
            {
                DialogResult result = MessageBox.Show("是否需要保存配置文件路径" + configFileName, "提示", MessageBoxButtons.YesNoCancel);
                if (result == DialogResult.Yes)
                {
                    configfil.LeftCameraConfigepath = configFileName;
                    textBox2.Text = configfil.LeftCameraConfigepath;
                    tool.SaveConfigFile(configfil);
                }
            }
        }

        private void button72_Click(object sender, EventArgs e)
        {
            HObject ho_ImageScaled;
            if (manualImage!=null)
            {
                HOperatorSet.ScaleImage(manualImage, out ho_ImageScaled, 30, 80);
                HOperatorSet.DispObj(ho_ImageScaled, hSmartWindowControl5.HalconWindow);
                hSmartWindowControl5.SetFullImagePart();
                ho_ImageScaled.Dispose();
            }
        }

        private void button73_Click(object sender, EventArgs e)
        {
            if (DraROI != null)
            {
                if (DraROI.ID != 0)
                {
                    string[] str = new string[] { "row1", "column1", "row2", "column2" };
                    try
                    {
                        HTuple hTuple = DraROI.GetDrawingObjectParams(str);
                        HOperatorSet.GenRectangle1(out HObject ROI, hTuple.LArr[0], hTuple.LArr[1], hTuple.LArr[2], hTuple.LArr[3]);
                        Algorithm.Get_Radius(manualImage, ROI, out HObject Ho_Corcle, out HTuple radius, out HTuple Row, out HTuple Column);
                        HOperatorSet.SetColor(hSmartWindowControl5.HalconWindow, "red");
                        //DraROI.ClearDrawingObject();
                        HOperatorSet.DispRegion(Ho_Corcle, hSmartWindowControl5.HalconWindow);

                        Feature feature = new Feature();
                        feature._Style = Feature_Style.ellipse;
                        feature.Name = GetName("椭圆", productList.Product_list[Now_Product_ID].FeaturesList.Count);
                        //feature.Name = "椭圆" + productList.Product_list[Now_Product_ID].FeaturesList.Count;
                        //feature.Region_Path = Directory.GetCurrentDirectory() + "\\Product\\" + productList.Product_list[Now_Product_ID].ProductName + "\\Region" + productList.Product_list[Now_Product_ID].FeaturesList.Count + ".hobj";
                        feature.Region_Path = Directory.GetCurrentDirectory() + "\\Product\\" + productList.Product_list[Now_Product_ID].ProductName + "\\" + feature.Name + ".hobj";
                        feature.Region_Path = feature.Region_Path.Replace("椭圆", "Ellipse");
                        HOperatorSet.WriteRegion(ROI, feature.Region_Path);
                        productList.Product_list[Now_Product_ID].FeaturesList.Add(feature);
                        listBox1.Items.Add(feature.Name);

                    }
                    catch (Exception error)
                    {
                        MessageBox.Show(error.Message);
                    }
                    //DraROI.Dispose();
                }
            }
        }

        private void button74_Click(object sender, EventArgs e)
        {
            if (listBox1.SelectedIndex > -1)
            {
                if (productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.ellipse)
                {
                    textBox109.Text = listBox1.SelectedItem.ToString();
                }
                else
                {
                    MessageBox.Show("选择的特征类型错误");
                }

            }
        }

       

        private void CekBoxCompensationValueL_CheckedChanged(object sender, EventArgs e)
        {
            if (CekBoxCompensationValueL.Checked == true)
            {
                CekBoxCompensationValueL.Checked = true;
                CompensationValueL = true;
                CompensationValueR = false;
                CekBoxCompensationValueR.Checked = false;
                listBox2_SelectedIndexChanged(null,null);
            }
        }

        private void CekBoxCompensationValueR_CheckedChanged(object sender, EventArgs e)
        {
            if (CekBoxCompensationValueR.Checked == true)
            {
                CekBoxCompensationValueR.Checked = true;
                CompensationValueR = true;
                CompensationValueL = false;
                CekBoxCompensationValueL.Checked = false;
                listBox2_SelectedIndexChanged(null, null);
            }
        }

        private void button75_Click(object sender, EventArgs e)
        {
            if (listBox8.SelectedIndex > -1)
            {
                if (listBox8.SelectedItem.ToString() == productList.Product_list[Now_Product_ID].HikProductName)
                {
                    listBox8.Items.RemoveAt(listBox8.SelectedIndex);
                    productList.Product_list[Now_Product_ID].HikProductName = " ";
                    productList.Product_list[Now_Product_ID].HikStandraModel_Path = " ";
                    productList.Product_list[Now_Product_ID].Pinchek = false;
                    return;
                }
                productList.Product_list[Now_Product_ID].FeaturesList.RemoveAt(listBox8.SelectedIndex);
                listBox8.Items.RemoveAt(listBox8.SelectedIndex);
                MessageBox.Show("删除成功");
            }
        }

        private void button46_Click(object sender, EventArgs e)
        {
            try
            {
                PinCheck pincheck = new PinCheck();
                if (productList.Product_list[Now_Product_ID].HikStandraModel_Path != null)
                {
                    HOperatorSet.ReadRegion(out HObject Region, productList.Product_list[Now_Product_ID].HikStandraModel_Path);
                    for (int i = 0; i < productList.Product_list[Now_Product_ID].MeasureList.Count; i++)
                    {
                        if (productList.Product_list[Now_Product_ID].MeasureList[i].PinName != "")
                        {
                            pincheck = productList.Product_list[Now_Product_ID].MeasureList[i].MeasurePin(hSmartWindowControl5, manualImage, Region, HikRightCameraParam, HikRightPose,"Right");

                        }
                    }
                    if (pincheck.TestReult == false)
                    {
                       
                    }
                }
                else
                {
                    MessageBox.Show("未找到匹配图像路径");
                }

            }
            catch (Exception error)
            {
                MessageBox.Show("错误!" + error.Message);
            }


        }

        private void button76_Click(object sender, EventArgs e)
        {
            ProductTotal.TotalClear();
            this.BeginInvoke((Action<Label>)(theLable => { theLable.Text = "0"; }), label136);
            this.BeginInvoke((Action<Label>)(theLable => { theLable.Text = "0"; }), label138);
            this.BeginInvoke((Action<Label>)(theLable => { theLable.Text = "0"; }), label140);
        }

        private void button81_Click(object sender, EventArgs e)
        {

            if (textBox114.Text != "" && textBox115.Text != "" && textBox116.Text != "")
            {
                HOperatorSet.GetImageSize(manualImage, out HTuple width, out HTuple height);
                HOperatorSet.ReadRegion(out HObject hObject, productList.Product_list[Now_Product_ID].FeaturesList[Region1nenumber].Region_Path);
                HOperatorSet.ReadRegion(out HObject hObject1, productList.Product_list[Now_Product_ID].FeaturesList[Region2nenumber].Region_Path);
                HOperatorSet.ReadRegion(out HObject hObject2, productList.Product_list[Now_Product_ID].FeaturesList[Region3nenumber].Region_Path);
                Algorithm.Get_Radius(manualImage, hObject, out HObject Ho_Corcle, out HTuple radius, out HTuple Row, out HTuple Column);
                Algorithm.Get_Radius(manualImage, hObject1, out HObject Ho_Corcle1, out HTuple radius1, out HTuple Row1, out HTuple Column1);
                Algorithm.Get_Radius(manualImage, hObject2, out HObject Ho_Corcle2, out HTuple radius2, out HTuple Row2, out HTuple Column2);
                HOperatorSet.GenRegionLine(out HObject regionline1, Row, Column, Row1, Column1);
                //Algorithm.GetlineL(Row, Column, Row1, Column1, out HTuple hv_Deg, out HTuple hv_RowStart, out HTuple hv_ColStart, out HTuple hv_RowEnd, out HTuple hv_ColEnd);
                //HOperatorSet.GenRegionLine(out HObject regionline1L, hv_RowStart, hv_ColStart, hv_RowEnd, hv_ColEnd);
                HOperatorSet.ProjectionPl(Row2, Column2, Row, Column, Row1, Column1, out HTuple rowProj, out HTuple colProj);
                HOperatorSet.GenRegionLine(out HObject regionline2, Row2, Column2, rowProj, colProj);
                //Algorithm.GetlineL(Row2, Column2, rowProj, colProj, out HTuple hv_Deg1, out HTuple hv_RowStart1, out HTuple hv_ColStart1, out HTuple hv_RowEnd1, out HTuple hv_ColEnd1);
                //HOperatorSet.GenRegionLine(out HObject regionline2L, hv_RowStart1, hv_ColStart1, hv_RowEnd1, hv_ColEnd1);
                HOperatorSet.SetColor(hSmartWindowControl5.HalconWindow, "red");
                HOperatorSet.DispRegion(regionline1, hSmartWindowControl5.HalconWindow);
                HOperatorSet.SetColor(hSmartWindowControl5.HalconWindow, "red");
                HOperatorSet.DispRegion(regionline2, hSmartWindowControl5.HalconWindow);
                Feature feature = new Feature();
                feature._Style = Feature_Style.LineXY;
                feature.Name = GetName("基准轴", productList.Product_list[Now_Product_ID].FeaturesList.Count) + "_" + productList.Product_list[Now_Product_ID].FeaturesList[Region1nenumber].Name + "," + productList.Product_list[Now_Product_ID].FeaturesList[Region2nenumber].Name;
                //feature.Name = "直线" + productList.Product_list[Now_Product_ID].FeaturesList.Count;
                feature.LineStartPoint.Row = Row;
                feature.LineStartPoint.Column = Column;
                feature.LineEndPoint.Row = Row1;
                feature.LineEndPoint.Column = Column1;
                feature.Region_Path = Directory.GetCurrentDirectory() + "\\Product\\" + productList.Product_list[Now_Product_ID].ProductName + "\\Region" + productList.Product_list[Now_Product_ID].FeaturesList.Count + ".hobj";
                HOperatorSet.WriteRegion(regionline1, feature.Region_Path);
                productList.Product_list[Now_Product_ID].FeaturesList.Add(feature);
                listBox1.Items.Add(feature.Name);

                Feature feature1 = new Feature();
                feature1._Style = Feature_Style.LineXY;
                feature1.Name = GetName("基准轴", productList.Product_list[Now_Product_ID].FeaturesList.Count) + "_" + productList.Product_list[Now_Product_ID].FeaturesList[Region3nenumber].Name;
                //feature.Name = "直线" + productList.Product_list[Now_Product_ID].FeaturesList.Count;
                feature1.LineStartPoint.Row = Row2;
                feature1.LineStartPoint.Column = Column2;
                feature1.LineEndPoint.Row = rowProj;
                feature1.LineEndPoint.Column = colProj;
                feature1.Region_Path = Directory.GetCurrentDirectory() + "\\Product\\" + productList.Product_list[Now_Product_ID].ProductName + "\\Region" + productList.Product_list[Now_Product_ID].FeaturesList.Count + ".hobj";
                HOperatorSet.WriteRegion(regionline2, feature.Region_Path);
                productList.Product_list[Now_Product_ID].FeaturesList.Add(feature1);
                listBox1.Items.Add(feature1.Name);
                hObject.Dispose(); hObject1.Dispose(); hObject2.Dispose();
                Row.Dispose(); Column.Dispose(); Row1.Dispose(); Column1.Dispose(); Row2.Dispose(); Column2.Dispose();
                //hv_RowStart.Dispose(); hv_ColStart.Dispose(); hv_RowEnd.Dispose(); hv_ColEnd.Dispose();
                //hv_RowStart1.Dispose(); hv_ColStart1.Dispose(); hv_RowEnd1.Dispose(); hv_ColEnd1.Dispose();
            }
        }

        private void button80_Click(object sender, EventArgs e)
        {
            if (listBox1.SelectedIndex > -1)
            {
                if (productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.Circle || productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.SemiCircle || productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.ellipse)
                {
                    textBox114.Text = listBox1.SelectedItem.ToString();
                     Region1nenumber = listBox1.SelectedIndex;
    }
                else
                {
                    MessageBox.Show("选择的特征类型错误");
                }

            }
        }

        private void button79_Click(object sender, EventArgs e)
        {
            if (listBox1.SelectedIndex > -1)
            {
                if (productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.Circle || productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.SemiCircle || productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.ellipse)
                {
                    textBox116.Text = listBox1.SelectedItem.ToString();
                    Region2nenumber = listBox1.SelectedIndex;
                }
                else
                {
                    MessageBox.Show("选择的特征类型错误");
                }

            }
        }

        private void button78_Click(object sender, EventArgs e)
        {
            if (listBox1.SelectedIndex > -1)
            {
                if (productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.Circle || productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.SemiCircle || productList.Product_list[Now_Product_ID].FeaturesList[listBox1.SelectedIndex]._Style == Feature_Style.ellipse)
                {
                    textBox115.Text = listBox1.SelectedItem.ToString();
                    Region3nenumber = listBox1.SelectedIndex;
                }
                else
                {
                    MessageBox.Show("选择的特征类型错误");
                }

            }
        }

        private void hSmartWindowControl3_Load(object sender, EventArgs e)
        {

        }

        private void button77_Click(object sender, EventArgs e)
        {
            Test();
        }

        private void button77_Click_1(object sender, EventArgs e)
        {
            if (textBox114.Text != "" && textBox116.Text != "")
            {
                HOperatorSet.GetImageSize(manualImage, out HTuple width, out HTuple height);
                HOperatorSet.ReadRegion(out HObject hObject, productList.Product_list[Now_Product_ID].FeaturesList[Region1nenumber].Region_Path);
                HOperatorSet.ReadRegion(out HObject hObject1, productList.Product_list[Now_Product_ID].FeaturesList[Region2nenumber].Region_Path);
                Algorithm.Get_Radius(manualImage, hObject, out HObject Ho_Corcle, out HTuple radius, out HTuple Row, out HTuple Column);
                Algorithm.Get_Radius(manualImage, hObject1, out HObject Ho_Corcle1, out HTuple radius1, out HTuple Row1, out HTuple Column1);
                HOperatorSet.GenRegionLine(out HObject regionline1, Row, Column, Row1, Column1);
                //Algorithm.GetlineL(Row, Column, Row1, Column1, out HTuple hv_Deg, out HTuple hv_RowStart, out HTuple hv_ColStart, out HTuple hv_RowEnd, out HTuple hv_ColEnd);
                HOperatorSet.GenRegionLine(out HObject regionline1L, Row, Column, Row1, Column1);
                HOperatorSet.SetColor(hSmartWindowControl5.HalconWindow, "red");
                HOperatorSet.DispRegion(regionline1L, hSmartWindowControl5.HalconWindow);

                Feature feature = new Feature();
                feature._Style = Feature_Style.Line;
                feature.Name = GetName("点构线", productList.Product_list[Now_Product_ID].FeaturesList.Count) + "_" + productList.Product_list[Now_Product_ID].FeaturesList[Region1nenumber].Name + "," + productList.Product_list[Now_Product_ID].FeaturesList[Region2nenumber].Name;
                feature.LineStartPoint.Row = Row;
                feature.LineStartPoint.Column = Column;
                feature.LineEndPoint.Row = Row1;
                feature.LineEndPoint.Column = Column1;
                feature.Region_Path = Directory.GetCurrentDirectory() + "\\Product\\" + productList.Product_list[Now_Product_ID].ProductName + "\\" + feature.Name + ".hobj";
                feature.Region_Path = feature.Region_Path.Replace("直线", "Line");
                HOperatorSet.WriteRegion(regionline1, feature.Region_Path);
                productList.Product_list[Now_Product_ID].FeaturesList.Add(feature);
                listBox1.Items.Add(feature.Name);
                hObject.Dispose(); hObject1.Dispose();
                Row.Dispose(); Column.Dispose(); Row1.Dispose(); Column1.Dispose();
                //hv_RowStart.Dispose(); hv_ColStart.Dispose(); hv_RowEnd.Dispose(); hv_ColEnd.Dispose();

            }
        }
    }
}
